pipe.c
changeset 107 244356bc3a20
child 113 397270b5d21a
equal deleted inserted replaced
106:a540a842ddef 107:244356bc3a20
       
     1 /**
       
     2  * pipe.c
       
     3  * Copyright (C) 2009 Markus Broeker
       
     4  *
       
     5  */
       
     6 
       
     7 #include <stdio.h>
       
     8 #include <stdlib.h>
       
     9 #include <unistd.h>
       
    10 #include <wait.h>
       
    11 #include <assert.h>
       
    12 
       
    13 #define MAX 50
       
    14 
       
    15 int main (int argc, char **argv)
       
    16 {
       
    17     int tube[2];
       
    18     int i, status, count = 0;
       
    19 
       
    20     pid_t pid;
       
    21 
       
    22     char buffer[80];
       
    23 
       
    24     for (i = 0; i < MAX; i++) {
       
    25         if (pipe (tube) == -1) {
       
    26             perror ("PIPE");
       
    27 
       
    28             return EXIT_FAILURE;
       
    29         }
       
    30 
       
    31         pid = fork ();
       
    32         switch (pid) {
       
    33         case 0:
       
    34             // we only want to write
       
    35             close (tube[0]);
       
    36 
       
    37             /**
       
    38              * copy on write: every forked process gets its own copy of i
       
    39              *                and the magic of synchronization works
       
    40              */
       
    41             for (i = 0; i < MAX; i++)
       
    42                 status = write (tube[1], "MESSAGE FROM SON\n", 17);
       
    43             break;
       
    44 
       
    45         case -1:
       
    46             printf ("ERROR");
       
    47             break;
       
    48 
       
    49         default:
       
    50             printf ("Son started as pid %d\n", pid);
       
    51 
       
    52             // we only want to read...
       
    53             close (tube[1]);
       
    54 
       
    55             FILE *f = fdopen (tube[0], "r");
       
    56             assert (f != NULL);
       
    57             while (fgets (buffer, sizeof (buffer), f) != NULL) {
       
    58                 printf ("FATHER RECEIVED [%4d]: %s", count++, buffer);
       
    59             }
       
    60 
       
    61             if (fclose (f) < 0)
       
    62                 perror ("fclose");
       
    63 
       
    64             printf ("PID [%4d] has finished...\n", wait (&pid));
       
    65         }
       
    66     }
       
    67 
       
    68     return EXIT_SUCCESS;
       
    69 }