首页 文章

处理SIGCHLD时,睡眠功能无效

提问于
浏览
0

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 函数在执行中没有任何影响 . 这里有什么特别之处吗?

1 回答

  • 1

    来自documentation

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

    发生的事情是睡眠功能被信号处理程序中断 . 因此,检查它的返回值 60 . 如果这是意图,可以使用另一种策略来休眠剩余的秒数 .

相关问题