-1

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.

Gary Aitken
  • 233
  • 2
  • 12

1 Answers1

1

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.

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Not sure I understand. This implies the stdout of the child becomes the stdout of the exec'd process. Is that the case? – Gary Aitken Jul 27 '22 at 15:26
  • Thanks, that was the missing piece. I subsequently found this post https://stackoverflow.com/questions/12645236/c-read-stdout-from-multiple-exec-called-from-fork – Gary Aitken Jul 27 '22 at 15:44
  • `exec` doesn't create a process. It just changes the program being executed by the current process. The `dup2` sets the stdout of that one and only child process. – ikegami Jul 27 '22 at 16:52