//------------------------------------------------------------------- // racedemo.cpp // // This program shows the effects of a "race condition" which // can result when more than one process attempts to access a // common resource -- in this case, the stdout stream. It is // adapted from an example by W. Richard Stevens in "Advanced // Programming in the UNIX Environment" (1993). // // programmer: ALLAN CRUSE // written on: 10 OCT 2004 //------------------------------------------------------------------- #include // for perror(), setbuf(), putc() #include // for fork() #include // for exit() #define DELAY_COUNT 20000000 void one_character_at_a_time( char *msg ) { setbuf( stdout, NULL ); // set to 'unbuffered' while ( int c = *msg++ ) { putc( c, stdout ); int i = DELAY_COUNT; while( --i ); } } int main( void ) { int pid = fork(); if ( pid < 0 ) { perror( "fork" ); exit(1); } else if ( pid == 0 ) { one_character_at_a_time( "output from child process \n" ); } else { one_character_at_a_time( "output from parent process \n" ); } exit(0); }