POSIX Pipes Establishing a pipe to a child process


Example

File descriptors and FILE objects are per-process resources that cannot themselves be exchanged between processes via ordinary I/O. Therefore, in order for two distinct processes to communicate via an anonymous pipe, one or both participating processes must inherit an open pipe end from the process that created the pipe, which must therefore be the parent process or a more distant ancestor. The simplest case is the one in which a parent process wants to communicate with a child process.

Because the child process must inherit the needed open file description from its parent, the pipe must be created first. The parent then forks. Ordinarily, each process will be either strictly a reader or strictly a writer; in that case, each one should close the pipe end that it does not intend to use.

void demo() {
    int pipefds[2];
    pid_t pid;

    // Create the pipe
    if (pipe(pipefds)) {
        // error - abort ...
    }

    switch (pid = fork()) {
        case -1:
            // error - abort ...
            break;
        case 0:   /* child */
            close(pipefds[0]);
            write(pipefds[1], "Goodbye, and thanks for all the fish!", 37);
            exit(0);
        default:  /* parent */
            close(pipefds[1]);

            char buffer[256];
            ssize_t nread = read(pipefds[0], sizeof(buffer) - 1);

            if (nread >= 0) {
                buffer[nread] = '\0';
                printf("My child said '%s'\n", buffer);
            }

            // collect the child
            wait(NULL);

            break;
    }
}