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

标签 c process parent signals

#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;
}

我得到的结果是10秒后,子进程和父进程都打印出其消息然后退出。我期望子进程首先打印出消息,然后父进程将再休眠大约 20 秒,然后打印出消息并退出。为什么父进程在处理信号之前不恢复到“确切位置”,它又休眠了 20 秒?有什么办法可以实现这一目标吗?

最佳答案

sleep(3) 在出现信号时不会重新启动。

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.

所以你应该检查返回值并再次 sleep 。像(未经测试)的东西:

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

关于c - 为什么父进程在处理信号后没有返回到确切的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6878546/

相关文章:

select - Xpath - 如何根据 child 的属性选择 parent ?

c++ - error C2248,这是什么错误,我该如何解决?

c - 使用 include 指令初始化聚合

linux - 调用 fork() 时哪个进程先运行

java - 如何将 Java 和 jxbrowser 进程组合成单个自定义命名进程?

process - 带有序列号的 OpenSSL 签名

MySQL 使用多个表连接父记录

c - 在c中读取8位灰度bmp文件的问题

c - 如何从 C 程序创建 makefile?

C 对转换指针的相等运算符