send signal from parent process to child in C

2019-02-27 19:48发布

问题:

My child proccess can't start to work. I need to pass signal and execute readUsual function.

This is a small piece of code:

int main()
{
    pid_t pid2 = fork(); 
    if (pid2 < 0) 
        printf("Can't create child process\n");
    else if (pid2==0)
    {
        //this block never execute
        printf("Process2, pid=%d\n",getpid());
        signal(SIGUSR1,readUsual); 
    }
    else 
    {
        kill(pid2,SIGUSR1);
        printf("%s\n","Proccess1 end");
        for(;;);
    }

return 0;
}

回答1:

You need to either add synchronization in some way, or call signal() before your fork().

With your current code, you have no way to be sure child process call signal() before it receive the signal. Receiving the signal before the instruction to handle it will stop the child process.

Example:

#include <stdio.h>

#include <sys/types.h>
#include <signal.h>
#include <unistd.h>

static int received = 0;

void readUsual(int sig)
{
    if (sig == SIGUSR1)
    {
        received = 1;
    }
}

int main()
{
    signal(SIGUSR1,readUsual);

    pid_t pid2 = fork(); 
    if (pid2 < 0)
        printf("Can't create child process\n");
    else if (pid2==0)
    {
        printf("Process2, pid=%d\n",getpid());
        while (!received)
            ;
        printf("SIGUSR1 received.\n");
    }
    else 
    {
        kill(pid2,SIGUSR1);
        printf("%s\n","Proccess1 end");
        while (1)
            ;
    }

    return 0;
}

Example of output with this code:

Process1 end
Process2, pid=1397
SIGUSR1 received