Reputation: 425
I got a pipe.
int anotherPipe[2];
make(anotherPipe);
Both of the following processes have access to this pipe.
Process A:
close(anotherPipe[0]);
dup2(anotherPipe[1], 1); //redirect stdout to pipe
execl("/usr/bin/who", "usr/bin/who", NULL);
close(anotherPipe[1]); //this is never executed
Process B:
close(anotherPipe[1]);
read(anotherPipe[0], stringbuffer, bytestoread);
printf("%s\n", buffer);
printf("checkpoint\n");
close(anotherPipe[0]);
The "who" command's output from execl is redirected to process B via pipe, where it is printed. But now my process B is not terminating, although the checkpoint is printed.
By 'not terminating' I mean that the following is not displayed in the terminal:
myusername@ubuntucomputer:~$
What is happening here and how is it solved?
EDIT: Solved the issue with the non-terminating process B. It terminated, but my top level process finished before A and B, so the
myusername@ubuntucomputer:~$
was printed a lot earlier. I used waitpid() and now everything is fine.
Upvotes: 2
Views: 2357
Reputation: 780818
If execl()
is successful, nothing after it in the original program runs, since it replaces the contents of the process with the program you ask it to run. You need to close the pipe before execl
:
close(anotherPipe[0]);
dup2(anotherPipe[1], 1); //redirect stdout to pipe
close(anotherPipe[1]);
execl("/usr/bin/who", "usr/bin/who", (char*)NULL);
Also, don't forget to case NULL
to (char*)
when calling execl
. Since it's a variable-arguments function, it won't convert the type automatically.
Upvotes: 3