c - 处理 SIGCHLD 时 sleep 函数不起作用

标签 c operating-system signals multiple-processes

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/

相关文章:

c++ - 从信号处理程序打印堆栈跟踪

c - 如何将字符串类型传递给结构体

C语言: how memory alignment happened in the stack for array

Java - 即使文件不可读,file.length() 也会返回

bash:为什么我不能在后台 shell 中为 SIGINT 设置陷阱?

multithreading - 用于多处理的 Python 信号

c - osx - 在分配的内存页上写入和执行

c - C 中的除以 2 和无限循环

assembly - 实模式 x86 ASM : How are the Basics Done?

c - C中printk的atomic_long_t的打印格式是什么