开发者

Why doesn't parent process return to the exact location after handling signal?

#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>

sig_atomic_t child_exit_status;

void clean_up_child_process (int signal_number)
{
  /* Clean up the child process.  */
  int status;
  wait (&status);
  /* Store its exit status in a global variable.  */
  child_exit_status = status;
}

int main ()
{
  /* Handle SIGCHLD by calling clean_up_child_process.  */
  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.  */
  /* ...  */
  pid_t t = fork();
  if (t!=0) {
      // parent
      sleep(30);    // After handling signal, why does it not continue to sleep 20 (30-10) more seconds?
      printf("Parent exits\n");
  }
  else {
      // ch开发者_开发百科ild
      sleep(10);
      printf("child exists\n");
  }

  return 0;
}

The result that I got is after 10 seconds, both child and parent process prints out its message then exit. What I expect is child process prints out the message first, then parent process will sleep about 20 more seconds before printing out its message and exit. Why doesn't the parent process resume to "exact location" before handling signal, which is sleeping 20 more seconds? Is there a way that I can achieve this?


sleep(3) isn't restarted in the event of a signal.

Return Value: Zero if the requested time has elapsed, or the number of seconds left to sleep, if the call was interrupted by a signal handler.

So you should check the return value and sleep again. Something like (untested):

rc = 30;
while ((rc = sleep(rc)))
    ;


Consider that you may want to interrupt a blocking operation/select()/poll()/sleep(). One way to do it is to send a signal, which may cause the current function to exit with EINTR.

There is a SA_RESTART flag that causes some functions to be restarted on receipt of a signal, mainly read() and write(). Other functions' behaviour depends on implementation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜