【问题标题】:Sleep function has not effect when handling SIGCHLD处理 SIGCHLD 时休眠功能无效
【发布时间】:2018-12-10 01:04:35
【问题描述】:

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

【问题讨论】:

  • 检查sleep是否返回错误。

标签: c operating-system signals multiple-processes


【解决方案1】:

来自documentation

返回值

如果请求的时间已过或剩余的秒数,则为零 如果调用被信号处理程序中断,则休眠。

发生的情况是睡眠函数被信号处理程序中断。因此,检查它的返回值会看到 60。如果有意的话,可以使用另一种策略来休眠剩余的几秒钟。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多