Astinog
Astinog

Reputation: 1181

Standard output and Pipe use in exec

I'm having problems understanding the right use of the pipe in UNIX Systems. I have a main process which create a child process. The child process must run a different program from the father, he has to make some operation and then the child must communicate to the father the results. However in the child process I have to print on the terminal the partial results of these operations. I'm trying with a test program to do so, but I'm a bit stuck right now. This is the main test program

TEST.C

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(){

  int mypipe[2];
  pid_t pid;
  char readbuffer[6];

  pipe(mypipe);

  if((pid = fork()) == 0){
    close(mypipe[0]);
    dup2(mypipe[1], STDOUT_FILENO);
    execlp("./proc", "./proc", NULL);
  } else {

  wait(-1);
  close(mypipe[1]);
  read(mypipe[0], readbuffer, sizeof(readbuffer));
  printf("%s", readbuffer); 
  }
}

And the c file of the ./proc program is this: PROC.C

#include <stdio.h>

int main(int argc, char* argv[]){

  printf("check\n");

  return 0;
}

With this solution, the proc program can't print anything on the terminal. How do I make the proc program to print on the terminal AND on the pipe so the main program can read from there??? Thank you!

Upvotes: 0

Views: 84

Answers (2)

Simon PA
Simon PA

Reputation: 746

If you want your "proc" program to print in terminal for log/debug infos, u can use fprintf and stderr:

fprintf(stderr, "What you need to print\n");

You can also see where your program is writing, use strace

Upvotes: 1

doron
doron

Reputation: 28872

Even when you redirect stdout to the parent program, you can still use stderr. Just call fprintf(stderr, ...) instead of printf(...) when you want to print to the console.

Upvotes: 1

Related Questions