为什么父进程在处理信号后没有返回到确切的位置?

2 c signals process parent

#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 {
      // child
      sleep(10);
      printf("child exists\n");
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我得到的结果是10秒后,子进程和父进程都打印出它的消息然后退出.我期望的是子进程首先打印出消息,然后父进程将在打印出其消息并退出之前再睡20秒.为什么父进程在处理信号之前没有恢复到"确切位置",这是再睡20秒?我有办法实现这个目标吗?

cni*_*tar 5

sleep(3) 如果发出信号,则不会重新启动.

返回值:如果请求的时间已经过去,则为零; 如果呼叫被信号处理程序中断,则为剩余的秒数.

所以你应该检查返回值并重新入睡.像(未经测试)的东西:

rc = 30;
while ((rc = sleep(rc)))
    ;
Run Code Online (Sandbox Code Playgroud)