2016-10-19 37 views
1

我有2个过程让我们说A和B.过程A会从用户那里得到输入并做一些处理。如何从信号处理程序内部向其他进程发送通知?

有进程A和B.

之间没有父/子关系。如果进程A获得通过信号杀死,有什么办法我可以给从信号处理程序内部进程B的消息?

注意:对于我的要求,如果罚款一旦我完成处理已经接收到来自用户的输入并且如果收到SIGHUP信号则从主循环退出。

我在脑海中有下面的想法。这种设计有什么缺陷吗?

进程A

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

回答

1

试想,如果进程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 
} 
1

正如Jeegar在其他答案中所提到的,致命信号会中断进程主执行并调用信号处理程序。控制权不会回到中断的地方。因此,现在显示的代码在处理致命信号后决不会调用send_message_to_B

请注意您从信号处理程序调用哪些函数。某些功能被认为不安全,可以从信号处理程序中调用 - Refer section - Async-signal-safe functions

相关问题