我有两个进程,比如A和b,进程A将从用户那里获取输入并做一些处理。
进程A和进程b之间没有父/子关系。
如果进程A被信号杀死,是否有办法从信号处理程序内部将消息发送给进程B ?
注意:对于我的要求,如果很好,一旦我完成了处理已经从用户接收到的输入,如果接收到SIGHUP信号,则退出主循环。
我的脑子里有以下的想法。这个设计有什么缺陷吗? <标题>处理 #include <stdio.h>
#include <signal.h>
int signal;// variable to set inside signal handler
sig_hup_handler_callback()
{
signal = TRUE;
}
int main()
{
char str[10];
signal(SIGHUP,sig_hup_handler_callback);
//Loops which will get the input from the user.
while(1)
{
if(signal == TRUE) { //received a signal
send_message_to_B();
return 0;
}
scanf("%s",str);
do_process(str); //do some processing with the input
}
return 0;
}
/*function to send the notification to process B*/
void send_message_to_B()
{
//send the message using msg que
}
标题>如果进程A正在执行do_process(str);
并发生崩溃,则回调标志将被更新,但while循环将永远不会在下次调用,因此您的send_message_to_B();
将不会被调用。所以最好把这个函数放在回调中。
如下所示。
#include <stdio.h>
#include <signal.h>
int signal;// variable to set inside signal handler
sig_hup_handler_callback()
{
send_message_to_B();
}
int main()
{
char str[10];
signal(SIGHUP,sig_hup_handler_callback);
//Loops which will get the input from the user.
while(1)
{
scanf("%s",str);
do_process(str); //do some processing with the input
}
return 0;
}
/*function to send the notification to process B*/
void send_message_to_B()
{
//send the message using msg que
}
正如Jeegar在另一个回答中提到的,致命信号将中断进程主执行并调用信号处理程序。控制也不会回到被打断的地方。因此,现在显示的代码在处理致命信号后永远不会调用send_message_to_B
。
注意从信号处理程序中调用的函数。从信号处理程序调用一些函数被认为是不安全的——参见