Source code for namedpipe.c


    1: #include <stdio.h>
    2: #include <stdlib.h>
    3: #include <unistd.h>
    4: #include <sys/stat.h>
    5: #include <fcntl.h>
    6: 
    7: #define MAX_STRING    30
    8: #define MAX_MESSAGES    100
    9: #define FIFO_NAME    "buffer"
   10: 
   11: void Child( void );
   12: void Parent( void );
   13: void Error( char* sPrefix );
   14: 
   15: 
   16: int main( void )
   17: {
   18:     if ( mknod( FIFO_NAME, S_IFIFO | 0600, 0 ) < 0 )
   19:         Error( "mknod" );
   20:      
   21:     setbuf( stdout, NULL );
   22: 
   23:     if ( 0 == fork() )
   24:         Child();
   25:     else  {
   26:         Parent();
   27:         wait( 0 );
   28: 
   29:         unlink( FIFO_NAME );
   30:     }
   31: }
   32: 
   33: void Child( void )
   34: {
   35:     char sBuffer[ MAX_STRING ];
   36:     int  fd = open( FIFO_NAME, O_RDWR ),
   37:          i;
   38: 
   39:     if ( fd < 0 )
   40:         Error( "child fifo open" );
   41: 
   42:     for ( i = 1; i <= MAX_MESSAGES; ++i )  {
   43:         sprintf( sBuffer, "Line number %d", i );
   44:         printf( "Child sending '%s'\n", sBuffer );
   45: 
   46:         if ( write( fd, sBuffer, MAX_STRING ) < 0 )
   47:             Error( "child write" );
   48: 
   49:         /* sleep every now and then... */
   50:         if ( 0 == ( i % 25 ) )
   51:             sleep( 1 );
   52:     }
   53: 
   54:     close( fd );
   55: }
   56: 
   57: void Parent( void )
   58: {
   59:     char sBuffer[ MAX_STRING ];
   60:     int  fd = open( FIFO_NAME, O_RDWR ),
   61:          i;
   62: 
   63:     if ( fd < 0 )
   64:         Error( "parent fifo open" );
   65: 
   66:     for ( i = 0; i < MAX_MESSAGES; ++i )  {
   67:         if ( read( fd, sBuffer, MAX_STRING ) < 0 )
   68:             Error( "parent read" );
   69: 
   70:         printf( "Parent got '%s'\n", sBuffer );
   71: 
   72:         /* sleep every now and then */
   73:         if ( 0 == ( i % 20 ) )
   74:             sleep( 1 );
   75:     }
   76: }
   77: 
   78: void Error( char* sPrefix )
   79: {
   80:     perror( sPrefix );
   81:     exit( EXIT_FAILURE );
   82: }
   83: 
   84: