C - file descriptors, forks and pipes

Added a lot of comments from the original program and reordered when file handles are closed to make more sense (to me). Essentially I am not a rocket surgeon, so need more notes.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

/* from ch 7 Bach - The Design of the unix operating system */

char string[] = "hello world";

int main() {
    int count, i;
    int pid;
    int to_par[2], to_chil[2];      /* for pipes to parent, child */
    char buf[256];

    /* open a pair of pipes, input is 2 fd's */
    pipe(to_par);
    pipe(to_chil);

    if((pid = fork()) == 0) {
        /*
        fd  parent  child
        1     1  --->  0    to_chil
        0     0  <---  1    to_par
        */
        /* begin setup of the 2 way communication to parent */
        /* child process */
        /* from dup(2) */
        /* Dup() duplicates an existing object descriptor and */
        /* returns its value to the calling process */
        /* in this case it will be the lowest free fd, 0 */
        close(0);         /* close old stdin */
        dup(to_chil[0]);  /* dup pipe read to standard input */


        close(1);           /* close old stdout */
        /* in this case it will be the lowest free fd, 1 */
        dup(to_par[1]);     /*dup pipe write to stdout */

        /* close the original pairs */
        close(to_par[0]);
        close(to_par[1]);
        close(to_chil[0]);
        close(to_chil[1]);

        for(;;) {
            if ((count = read(0,buf, sizeof(buf))) == 0)
                exit(0);
            write(1, buf, count);
            fprintf(stderr, "child (pid = %d) (read from parent): %s\n", pid, buf);
        }
    }

    /* parent process executes here */
    close(1);
    dup(to_chil[1]);

    close(0);
    dup(to_par[0]);

    close(to_par[0]);
    close(to_par[1]);
    close(to_chil[0]);
    close(to_chil[1]);

    for(i = 0; i < 15; i++) {
        write(1, string, strlen(string));
        read(0,buf,sizeof(buf));
        fprintf(stderr,"parent (pid = %d) ( read from child): %s\n", pid, buf);
    }

} 

Published on in