Harsha Harsha - 2 months ago 15
C Question

user defined signals sigusr1 and sigusr2

I have am building a simple software in which there are multiple processes communicating with each other using the user defined signals SIGUSR1 and SIGUSR2.

I am just curious to know what happens in a scenario like what I am describing below.

"Process-1 did send sigusr1 to process-2 using kill command and the process-2 is executing the signal-handler doing some computation. Even before process-2 completed the execution of signal handler process-1 sends sigusr1 again to process-2. What would happen. I am unable to get a proper answer for this one. I think of two possible scenarios.


  1. The handler being executed currently gets interrupted ? or

  2. The second signal would be ignored by process-2.



Please advice me.

Answer

Processing signals take some time and if you send too much at a time, some could get ignored.

What you could do is send a response signal to the other process , basically saying :

Hey, I got your signal, send me the next one I'm ready

This way, no signal would get ignored and your program will get much faster with less to no errors.

If you want a cheap solution, just use usleep() and a small value (depend on your hardware actually)

Here is an example where an ascii message is sent to another process using signals :

Client - Sending part

void        decimal_conversion(char ascii, int power, int pid)
{
  if (power > 0)
    decimal_conversion(ascii / 2, power - 1, pid);
  if ((ascii % 2) == 1)
    kill(pid, SIGUSR1);
  else
    kill(pid, SIGUSR2);
  usleep(1);
}

void        ascii_to_binary(char *str, int pid)
{
  int       i;

  i = 0;
  while (str[i] != '\0')
    {
      decimal_conversion(str[i], 7, pid);
      i += 1;
    }
}

Server

void        sighandler(int signum)
{
  static int    ascii = 0;
  static int    power = 0;

  if (signum == SIGUSR1)
    ascii += 1 << (7 - power);
  if ((power += 1) == 8)
    {
      putchar(ascii);
      power = 0;
      ascii = 0;
    }
}

int     main(void)
{
  signal(SIGUSR1, sighandler);
  signal(SIGUSR2, sighandler);
  while (42);
  return (0);
}
Comments