I am fairly new to C so please bear with me if this is extremely basic. I have written a C program that emulates command line piping, as part of a larger program. I have got the pipe part to work, however once the final execvp()
is called, the program ends. I understand that I probably need to call another fork, however I have been trying to edit my code to do this and I have not been able to find a solution.
The code looks like this:
/* Code parsing commands into the array */
size_t i;
int prev_pipe, pfds[2];
prev_pipe = STDIN_FILENO;
for (i = 0; i < line_count - 2; i++)
{
pipe(pfds);
if (fork() == 0)
{
if (prev_pipe != STDIN_FILENO)
{
dup2(prev_pipe, STDIN_FILENO);
close(prev_pipe);
}
dup2(pfds[1], STDOUT_FILENO);
close(pfds[1]);
execvp(final_commands[i][0], final_commands[i]);
perror("execvp1 failed");
exit(1);
}
close(prev_pipe);
close(pfds[1]);
prev_pipe = pfds[0];
}
if (prev_pipe != STDIN_FILENO)
{
dup2(prev_pipe, STDIN_FILENO);
close(prev_pipe);
}
execvp(final_commands[i][0], final_commands[i]);
/* More code that I would like to run after exec has been called */
Any help would be greatly appreciated :)