问题描述
我正在尝试将用户定义的(SIGUSR1 或 SIGUSR2)信号从父进程发送到子进程.子进程接收到信号后,等待 5 秒,然后向父进程发送另一个用户定义的信号.当父进程接受信号时,它会向屏幕写入一个字符串.我无法弄清楚如何做到这一点.我正在尝试在 linux 终端上执行此操作.这是我的代码:
i am trying to send a user defined (SIGUSR1 or SIGUSR2) signal from parrent process to child process. After child process takes the signal, it waits for 5 seconds and sends another user defined signal to parrent process. When parrent process takes the signal, it writes a string to the screen. I cant figure it out how to do that. I am trying to do that on linux terminal. Here is my code:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
void wait_function(int signal_1)
{
signal(SIGUSR1,wait_function);
if(signal_1==SIGUSR1)
{
sleep(5);
}
}
void writeSomethingOnScreen(int signal_2)
{
signal(SIGUSR2,createAndWrite);
if(signal_2==SIGUSR2)
{
printf("Hello Stackoverflow!");
}
}
main()
{
pid_t pid;
pid=fork();
if(pid==0)/*child*/
{
signal(SIGUSR1,wait_function);
pause();
kill(getppid(),SIGUSR2);
exit(254);
}
if(pid>0)/*parent*/
{
signal(SIGUSR2,writeSomethingOnScreen);
kill(pid,SIGUSR1);
}
}
推荐答案
你在你的程序中提交了许多信号禁忌.我看到的最阴险的问题之一是赛车.在您fork
和为子进程注册信号处理程序之间有一个机会窗口在此期间SIGUSR1
可以发送和丢失强>.
You are committing many signal no-nos in your program. The most insidious problem that I see is one of racing. There is a window of opportunity between the time you fork
and the time you register a signal handler for the child during which a SIGUSR1
can be sent and lost.
看你的具体代码,想象这样一种情况,你fork
,父级获得第一个运行机会,在子级之前将SIGUSR1
发送给子级曾经建立了一个处理程序,这个信号永远丢失了.解决这个问题最简单的方法是在fork之前建立SIGUSR1
信号处理程序.
Looking at your specific code, imagine a situation where you fork
, the parent gets the first chance to run, sends SIGUSR1
to the child before the child ever established a handler and this signal is lost forever. The simplest way to solve this problem is to establish the SIGUSR1
signal handler before forking.
代码中的其他问题:
- 父进程在收到子进程的信号之前很久就退出了.也就是说,父母不只是等待它的孩子
- 睡在一个信号处理程序中是让大多数 Unix 程序员生气的事情.信号处理程序应该尽可能地短暂和简单
- 我认为没有理由在信号处理程序中重新建立信号处理程序 - 如果您想要持久"处理程序,请使用
sigaction
- 从信号处理程序中调用
printf
在技术上并不安全
- The parent process exits long before it has a chance to receive the signal from the child. That is, the parent doesn't just wait around for its children
- Sleeping in a signal handler is something that sets off most Unix programmers. A signal handler should be as short-lived and as simple as possible
- I see no reason why you reestablish signal handlers inside the signal handlers - if you want "persistent" handlers use
sigaction
- It is not technically safe to call
printf
from a signal handler
这篇关于在父进程和子进程之间发送信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!