Source code for pipes.c


    1: #include <stdio.h>
    2: #include <stdlib.h>
    3: 
    4: #define MAX_STRING      30
    5: #define MAX_MESSAGES    100
    6: 
    7: int main( void )
    8: {
    9:     int  i;
   10:     int  fd[ 2 ];
   11:     char s[ MAX_STRING ];
   12: 
   13:     setbuf( stdout, NULL );
   14: 
   15:     if ( pipe( fd ) < 0 )  {
   16:         perror( "pipe" );
   17:         exit( EXIT_FAILURE );
   18:     }
   19:     
   20:     if ( 0 == fork() )  {
   21:         /* child will write back to parent, so close read fd */
   22:         close( fd[ 0 ] );
   23: 
   24:         for ( i = 1; i <= MAX_MESSAGES; ++i )  {
   25:             sprintf( s, "Line number %d", i );
   26:             printf( "Child sending '%s'\n", s );
   27:             write( fd[ 1 ], s, MAX_STRING );
   28: 
   29:             /* sleep now and then, just for fun */
   30:             if ( 0 == ( i % 8 ) )
   31:                 sleep( 1 );
   32:         }
   33: 
   34:         close( fd[ 1 ] );
   35:     }
   36:     else  {
   37:         /* parent will read from child, so close write fd */
   38:         close( fd[ 1 ] );
   39: 
   40:         for ( i = 0; i < MAX_MESSAGES; ++i )  {
   41:             read( fd[ 0 ], s, MAX_STRING );
   42:             printf( "Parent got '%s'\n", s );
   43:         }
   44: 
   45:         close( fd[ 0 ] );
   46:         
   47:         /* wait for child */
   48:         wait( 0 );
   49:     }
   50: }
   51: 
   52: