Sample code without error handling
int pipes[2];
pipe(pipes);
int pid = fork();
if (pid == CHILD)
{
close(pipes[0]); //close useless read fd
dup2(STDOUT_FILENO, pipes[1]); //replace default output by writer piped fd
execve(...);
close(pipes[1]); // ??????????
}
else //parent
{
close(pipes[1]); //close useless write fd
dup2(STDIN_FILENO, pipes[0]); //replace default input by reader piped fd
read(pipes[0]..);
close(pipes[0]);
}
In the child, we know that a default output/input is automatically closed at the end of the program (STDIN_FILENO/STDOUT_FILENO).
If I use dup2()
to change the default input/output, will my pipes[1] be closed automatically? Or Have I to do it myself and then how? I'm thinking that execve
stops my program on its line on success.