为什么子进程不回复父进程发送的信号?

时间:2012-10-28 04:07:34

标签: c signals

我正在学习进程间通信的信号,我在下面编写了非常简单的测试代码:

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

void sighup();
void sigint();
void sigquit();

int main(int argc, const char *argv[])
{
    int child_pid;
    if((child_pid = fork()) < 0) exit (1);
    if(child_pid == 0) {
        sleep(2);
        signal(SIGHUP, sighup);
        signal(SIGINT, sigint);
        signal(SIGQUIT, sigquit);
        puts("this is the end of the child process");
    } else {
        printf("\n Parent: sending SIGHUP signal to child\n\n");
        kill(child_pid, SIGHUP);
        printf("\n Parent: sending SIGINT signal to child\n\n");
        kill(child_pid, SIGINT);
        printf("\n Parent: sending SIGQUIT signal to child\n\n");
        kill(child_pid, SIGQUIT);
    }
}

void sighup() {
    signal(SIGHUP, sighup);
    printf("CHILD: I have received a SIGHUP\n");
}
void sigint() {
    signal(SIGINT, sigint);
    printf("CHILD: I have received a SIGINT\n");
}

void sigquit() {
    sleep(2);
    printf("CHILD: My parent process has killed me!!");
    printf("CHILD: cleaning up...\n");
    exit(0);
}

似乎子进程没有做任何事情,甚至不打印进程字符串的结尾。任何想法?

1 个答案:

答案 0 :(得分:1)

由于竞争条件,您的孩子不会调用您的信号处理程序。父线程在子调用signal()之前向子线程发送信号,该信号覆盖信号处理行为。

在这种情况下,子进程收到SIGINT并执行其默认行为,即终止。因此,孩子在sleep(2)之后执行语句之前终止。