Search code examples
cforkchild-process

Does wait() disrupt the main process?


The following is the main part of my code ( adopted from "advanced linux programming", Listing 3.7 ):

void clean_up_child_process ( int signal_number ) {
  /* Clean up the child process. */
  int status ;
  wait ( &status ) ;

  printf ( " wait finished \n" ) ;

  /* Store its exit status in a global variable. */
  child_exit_status = status ;
}

int main() {
  /* Handle SIGCHLD by calling clean_up_child_process. */
  pid_t child_pid ;
  struct sigaction sigchld_action ;
  memset ( &sigchld_action, 0, sizeof(sigchld_action) ) ;
  sigchld_action.sa_handler = &clean_up_child_process ;

  sigaction ( SIGCHLD, &sigchld_action, NULL ) ;

  /* Now do things, including forking a child process */
  child_pid = fork () ;

  if ( child_pid > 0 ) {
    sleep ( 60 ) ; // it ends after only 15 seconds
  } else {
    sleep ( 15 ) ;
  exit (0) ;
  }

  printf ( "%d\n", child_exit_status ) ;
  return 0 ;
}

My conjecture is that the program takes about 60 seconds to finish. However what is actually happening is: once started, it runs for only about 15 seconds immediately after the the termination of the child process. I wonder why sleep ( 60 ) does not cause the main process to last for a while, or it is disrupted by wait() function.


Solution

  • If you read a sleep manual page you will see that the function

    sleep either until the number of real-time seconds specified in seconds have elapsed or until a signal arrives which is not ignored.

    [Emphasis mine]

    Since you don't ignore the SIGCHLD signal, the sleep function will be interrupted when the child exits and the parent process get the signal.