从父进程向C中的子进程发送信号 [英] send signal from parent process to child in C

查看:351
本文介绍了从父进程向C中的子进程发送信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的孩子进程无法开始工作.我需要传递信号并执行readUsual函数.

这是一小段代码:

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

推荐答案

您需要以某种方式添加同步,或者在fork()之前调用signal().

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

使用当前代码,您无法确保子进程调用signal()在收到信号之前无法确定.在处理指令之前接收信号将终止子进程.

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.

示例:

#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

这篇关于从父进程向C中的子进程发送信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆