Reputation: 103
Hi could somebody explain why I should use execlp after I close my pipes?
Here is an example:
if( cid == 0)
{//Only child cid can run this code
char msg[256];
//Redirect output into the pipe instead of the terminal
dup2(pipe1Fds[1],STDOUT_FILENO);
//Close pipes or the pipe reader will not get an EOF
close(pipe1Fds[0]);
close(pipe1Fds[1]);
close(pipe2Fds[0]);
close(pipe2Fds[1]);
//Execute cmd1
execlp(cmd1,cmd1,(char *)0);
exit(0);
}
Upvotes: 0
Views: 97
Reputation: 8326
You have dup2
'd the pipe FD to the STDOUT FD, so you don't need it anymore and need to close it (so it has an EOF for the reader).
The program executed by execlp
(if it has output) thinks its writing to STDOUT, but the STDOUT FD was changed to the pipe FD, so its writing to the pipe FD.
Upvotes: 1
Reputation: 3162
execlp() is going to load a different code into this process and then runs the new program therefore you need to close the pipe before loading the target code because the target code will not be accessing the pipe.
you can read this to get more information link. since your code is going to get replaced by program loaded by execlp() you must close pipes before calling execlp().
Upvotes: 1