简体   繁体   中英

Why the child process doesn't reply to the signal sent from parent process?

I'm learning the signal of inter process communication, I made the very simple test code below:

#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);
}

It seems like the child process doesn't do anything, even doesn't print the end of the process string. any idea?

Your signal handlers are not being invoked in the child because of a race condition. The parent thread sends the child thread a signal before the child calls signal() that overrides the signal handling behavior.

In this case, the child receives a SIGINT and performs its default behavior, which is to terminate. Thus the child terminates before executing the statements after sleep(2) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM