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:

  1. Create the pipe

  2. fork()

  3. The child uses dup2() to move filedes[1] to standard out.

  4. The child exec()s a program.

  5. The parent reads the program’s output from filedes[0]. After ...

Get Advanced Mac OS X Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.