Search code examples
clinuxpipeforkexecve

linux, how to fork and exec a process whose stdout can be read by the parent process


I can't figure out how to exec a process and read its stdout. It seems like this should be a combination of fork() and execve(), but I can't figure out how to get the pipes connected.

I know how to create a pipe and fork, and read the pipe written by the child process in the parent process;

I know how to execve to replace a process with another process.

What I don't understand is how to pass an open pipe from the forked child to the exec'ed process (I would like the pipe to be the exec'ed processes' stdout) for reading by the original parent.

e.g. parent         =>  child   =>   new-prog
 (creates pipe)    fork       execve (I want the pipe to be stdout of new-prog)
 (reads pipe)                        (writes pipe/stdout)

Any pointers / examples would be much appreciated.


Solution

  • The missing step is using dup2 in the child (pre-exec) to copy the pipe fd onto stdout. Don't forget to close the pipe fd after doing this.

    1. Create a pipe. Let's call its ends r and w.
    2. Fork.
      • Child:
        1. Close r.
        2. Use dup2 clone w onto stdout.
        3. Close w.
        4. Exec.
      • Parent:
        1. Close w.
        2. ...

    Error checking left out for clarity.