简体   繁体   中英

How to send notification to other process from inside Signal handler?

I have 2 process lets say A and B. process A will get the input from user and do some processing.

There is no parent/child relation between process A and B.

If process A get killed by a signal, Is there any way i can send the message to process B from inside signal handler ?

Note: For my requirement it if fine that once i done with processing already received input from the user and exit from main loop if SIGHUP signal is received.

I am having following idea in my mind. Is there any flaw in this design ?

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

Just think if process A is executing do_process(str); and crash happen then in call back Flag will be updated but you while loop will never called for next time so your send_message_to_B(); will not be called. So better to put that function in callback only..

Just as below.

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

As mentioned by Jeegar in the other answer, fatal signals will interrupt the process main execution and have the signal handler called. And the control won't be back to where it was interrupted. Hence your code as it is shown now will never call send_message_to_B after handling fatal signal.

Be careful on what functions you invoke from the signal handlers. Some functions are considered not safe to be called from signal-handlers - Refer section - Async-signal-safe functions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM