#include #include #include #include #include /* function prototypes */ int child(); void parent( int children ); int main() { int i, children = 8; /* based on a true story..... */ /* srand( time( NULL ) ); */ for ( i = 0 ; i < children ; i++ ) { pid_t z = fork(); if ( z < 0 ) { fprintf( stderr, "ERROR: fork() failed.\n" ); exit( 1 ); } if ( z == 0 ) { int rc = child(); exit( rc ); } } parent( children ); return 0; } int child() { int t; printf( "CHILD: I'm new. My pid is %d.\n", getpid() ); /* srand( time( NULL ) ); */ srand( time( NULL ) * getpid() * getpid() ); t = 10 + ( rand() % 21 ); /* [10,30] */ printf( "CHILD: I'm gonna nap for %d seconds\n", t ); sleep( t ); return t; } void parent( int children ) { int status; /* return status from a child */ pid_t child_pid; printf( "PARENT: I'm waiting for children.\n" ); while ( children > 0 ) { /* wait until a child process exits */ child_pid = wait( &status ); /* BLOCKS */ children--; printf( "PARENT: child process %d exited...", child_pid ); if ( WIFSIGNALED( status ) ) /* e.g. core dump */ { printf( "...abnormally\n" ); } else if ( WIFEXITED( status ) ) { int rc = WEXITSTATUS( status ); printf( "...after sleeping %d seconds\n", rc ); } printf( "PARENT: %d more to go\n", children ); } printf( "PARENT: All done.\n" ); }