2016-10-19 48 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

相關問題