0

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 :)

nug_123
  • 1
  • 1
  • At the risk of sounding overtly self-gratifying, you may find [this answer](https://stackoverflow.com/questions/19356075/toy-shell-not-piping-correctly/19357317#19357317) to a similar question informative. – WhozCraig May 15 '22 at 11:33
  • 1
    If `execvp()` or one of it's relatives succeeds, it doesn't return; if it returns, it failed. There is no way for the original program to continue after a successful `exec*()` function. Yes, you will need to `fork()` again. Or use `system()` to do it for you, but that probably isn't the right choice. – Jonathan Leffler May 15 '22 at 11:42

0 Answers0