SIGCHLD
处理和 sleep
函数之间有什么关系?
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
sig_atomic_t child_exit_status;
void clean_up_child_process(int signal_number)
{
int status;
wait(&status);
child_exit_status = status;
}
int main()
{
struct sigaction sigchld_action;
memset(&sigchld_action, 0, sizeof(sigchld_action));
sigchld_action.sa_handler = &clean_up_child_process;
sigaction(SIGCHLD, &sigchld_action, NULL);
pid_t child_pid = fork();
if (child_pid > 0) {
printf("Parent process, normal execution\n");
sleep(60);
printf("After sleep\n");
} else {
printf("Child\n");
}
return 0;
}
因为当我执行上面的代码时,它会打印:
Parent process, normal execution
Child
After sleep
但是执行中sleep
函数没有任何作用。这里发生的事情有什么特殊性吗?
最佳答案
来自documentation :
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 函数被信号处理程序中断。因此检查它的返回值可以看到60
。如果有意的话,可以使用另一种策略来休眠剩余的几秒。
关于c - 处理 SIGCHLD 时 sleep 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53698270/