简体   繁体   中英

Why does SIGUSR1 terminate my child process although signal() function has been used?

I have the following code:

void sig_handler(int sig) {
    printf("Hello child\n");
}

int main()
{
    pid_t child = fork();
    if (child > 0)
    {
        printf("Hello parent\n");
        kill(child, SIGUSR1);
    }
    else if (child == 0)
    {
        signal(SIGUSR1, sig_handler);
        printf("In child\n");
    }
    else
    {
        printf("Error\n");
    }
    return 0;
}

I want the code to run:

Hello parent
Hello child
In child

But the child is killed immediately after the parent sends kill(child, SIGUSR1); , and the result is just:

Hello parent

I have read document that the dafault action of the SIGUSR1 is termination, however, I have already implemented the signal handler signal(SIGUSR1, sig_handler); for catching the SIGUSR1 , then why is the child still killed?

I'd say there are two possibilities: either the son process dies before the main process sends the signal, or the main process sends the signal before the handler is set.

Edit: if you only get "Hello parent" it can't be the first one.

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