Pipes
Open files are inherited across an exec() unless you explicitly tell the file descriptors to “close on exec.” This behavior forms the basis of building pipelines between programs. A process calls pipe() to create a communications channel before fork()ing:
int pipe (int fildes[2]);pipe() fills the filedes array with two file descriptors that are connected in such a way that data written to filedes[1] can be read from filedes[0]. If you wanted to fork() and exec() a command and read that command’s output, you would do something like this, as illustrated in Figure 18.5:
Create the pipe
fork()
The child uses dup2() to move filedes[1] to standard out.
The child exec()s a program.
The parent reads the program’s output from filedes[0]. After ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access