send signal from parent process to child in C

爱⌒轻易说出口 提交于 2019-12-09 03:51:28

问题


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


来源:https://stackoverflow.com/questions/36234703/send-signal-from-parent-process-to-child-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!