#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/