home *** CD-ROM | disk | FTP | other *** search
/ ftp.disi.unige.it / 2015-02-11.ftp.disi.unige.it.tar / ftp.disi.unige.it / pub / .person / GianuzziV / SO1 / fork3.c < prev    next >
C/C++ Source or Header  |  2001-11-07  |  1KB  |  60 lines

  1. /* fork3.c */
  2.  
  3. #include <string.h>
  4. #include <fcntl.h>
  5. char    stringa[20];
  6. int     i;
  7.  
  8. /* Due processi comunicano attraverso due pipe, uno
  9.    da padre a figlio, l'altro da figlio a padre.
  10.  
  11.        ------to_chil--------
  12.        |                   |
  13.        |                   V
  14.       padre              figlio
  15.        ^                   |
  16.        |                   |
  17.        ------from_chil-----
  18. */
  19.  
  20. main (argc, argv)
  21. int     argc;
  22. char    *argv[];
  23. {  int    cont, i, status, c = 0;
  24.    int    to_chil[2], from_chil[2];   /* pipe dal padre e pipe dal figlio */
  25.    char    buf[256];
  26.  
  27.    pipe (to_chil);
  28.    pipe (from_chil);
  29.    if ( fork() == 0 )
  30.    { /* processo figlio */
  31.      close(to_chil[1]);
  32.      close(from_chil[0]);
  33.      for (;;)
  34.      { for (i=0; i<256; i++) buf[i]='\0';
  35.        if ((cont = read(to_chil[0], buf, sizeof(buf))) == 0) 
  36.          {printf("fine pipe, letti %d stringhe \n",c);
  37.           exit(3); }
  38.        printf("letto da pipe %s \n", buf);
  39.        c++;
  40.        write (from_chil[1], buf, cont);
  41.      }
  42.    }
  43.    /* processo padre */
  44.    close(from_chil[1]);
  45.    close(to_chil[0]);
  46.    for ( i=0; i<15; i++)
  47.    { printf("scrivere stringa da inviare ");
  48.      scanf("%s",stringa);
  49.      cont = write (to_chil[1], stringa, strlen(stringa));
  50.      c++;
  51.      cont = read(from_chil[0], buf, sizeof(buf));
  52.    }
  53.    printf("scritte %d stringhe. \n",c);
  54.    close(to_chil[1]);
  55.    close(from_chil[0]);
  56.    wait(&status);
  57.    printf("%x \n",status);
  58. }
  59.  
  60.