#include #include #include #include #include #define MAX_STRING 30 #define MAX_MESSAGES 100 #define FIFO_NAME "buffer" void Child( void ); void Parent( void ); void Error( char* sPrefix ); int main( void ) { if ( mknod( FIFO_NAME, S_IFIFO | 0600, 0 ) < 0 ) Error( "mknod" ); setbuf( stdout, NULL ); if ( 0 == fork() ) Child(); else { Parent(); wait( 0 ); unlink( FIFO_NAME ); } } void Child( void ) { char sBuffer[ MAX_STRING ]; int fd = open( FIFO_NAME, O_RDWR ), i; if ( fd < 0 ) Error( "child fifo open" ); for ( i = 1; i <= MAX_MESSAGES; ++i ) { sprintf( sBuffer, "Line number %d", i ); printf( "Child sending '%s'\n", sBuffer ); if ( write( fd, sBuffer, MAX_STRING ) < 0 ) Error( "child write" ); /* sleep every now and then... */ if ( 0 == ( i % 25 ) ) sleep( 1 ); } close( fd ); } void Parent( void ) { char sBuffer[ MAX_STRING ]; int fd = open( FIFO_NAME, O_RDWR ), i; if ( fd < 0 ) Error( "parent fifo open" ); for ( i = 0; i < MAX_MESSAGES; ++i ) { if ( read( fd, sBuffer, MAX_STRING ) < 0 ) Error( "parent read" ); printf( "Parent got '%s'\n", sBuffer ); /* sleep every now and then */ if ( 0 == ( i % 20 ) ) sleep( 1 ); } } void Error( char* sPrefix ) { perror( sPrefix ); exit( EXIT_FAILURE ); }