#include #include #include #include #include #include int child(); void * kill_zombies( int n ) { int status; printf( "PARENT: Caught a SIGCHLD (%d). I'm trying to sleep!\n", n ); waitpid( 0, &status, WNOHANG ); /* some versions of Unix reset the signal handler to SIG_DFL */ signal( SIGCHLD, kill_zombies ); return (void *)NULL; } int main() { int i, children = 8; /* based on a true story .... */ for ( i = 0 ; i < children ; i++ ) { /* fork a child process */ pid_t z = fork(); if ( z < 0 ) { fprintf( stderr, "ERROR: fork() failed.\n" ); exit( 1 ); } if ( z == 0 ) { int rc = child(); exit( rc ); } } { int t = 40; printf( "PARENT: I don't care. I'm busy. Don't bother me.\n" ); signal( SIGCHLD, kill_zombies ); do { t = sleep( t ); } while ( t > 0 ); } return 0; } void * handle_sigint( int n ) { printf( "CHILD: Caught SIGINT (%d). Okay, I'm awake!\n", n ); return (void *)NULL; } int child() { int t; printf( "CHILD: I'm new. My pid is %d.\n", getpid() ); signal( SIGINT, handle_sigint ); srand( getpid() * getpid() ); t = 10 + ( rand() % 21 ); /* in range [10,30] */ printf( "CHILD: I'm gonna nap for %d seconds.\n", t ); t -= sleep( t ); return t; }