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.
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.
r
and w
.r
.dup2
clone w
onto stdout.w
.w
.Error checking left out for clarity.