pipe.c
author Markus Brökers <mbroeker@largo.homelinux.org>
Mon, 30 Aug 2010 15:21:47 +0200
changeset 146 0ffa20c26b2d
parent 140 05d42a3737a4
permissions -rw-r--r--
gauss.c: set a proper accuracy value: 1E-6

/**
 * pipe.c
 * Copyright (C) 2009 Markus Broeker
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <assert.h>

#define MAX 50

int main (int argc, char **argv)
{
    int tube[2];
    int i, status, count = 0;

    pid_t pid;

    char buffer[80];

    for (i = 0; i < MAX; i++) {
        if (pipe (tube) == -1) {
            perror ("PIPE");

            return EXIT_FAILURE;
        }

        pid = fork ();
        switch (pid) {
        case 0:
            // we only want to write
            close (tube[0]);

            /**
             * copy on write: every forked process gets its own copy of i
             *                and the magic of synchronization works
             */
            for (i = 0; i < MAX; i++)
                status = write (tube[1], "MESSAGE FROM SON\n", 17);
            break;

        case -1:
            printf ("ERROR");
            break;

        default:
            printf ("Son started as pid %d\n", pid);

            // we only want to read...
            close (tube[1]);

            FILE *f = fdopen (tube[0], "r");
            assert (f != NULL);
            while (fgets (buffer, sizeof (buffer), f) != NULL) {
                printf ("FATHER RECEIVED [%4d]: %s", count++, buffer);
            }

            if (fclose (f) < 0)
                perror ("fclose");

            printf ("PID [%4d] has finished...\n", wait (&pid));
        }
    }

    return EXIT_SUCCESS;
}