C wait for signal with loop

Viewed 11449

In C Linux, is there any way to wait for signal like SIGUSR1 and SIGUSR2 without loop?

For eaxmple in this code I wait for SIGUSR1 or SIGUSR2 to print message, but while I want , I do while true....

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

void signal_callback_handler(int signum)
{
   printf("Caught signal %d\n",signum); 
}

int main()
{
   signal(SIGUSR1, signal_callback_handler);
   signal(SIGUSR2, signal_callback_handler);
   while(1)
   {
      printf("Program processing stuff here.\n");
      sleep(1);
   }
   return EXIT_SUCCESS;
}

How can I wait and do not do anything (do not do while true) until SIGUSR1 or SIGUSR2 arrived ?

For example :

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

void signal_callback_handler(int signum)
{
   printf("Caught signal %d\n",signum); 
}

int main()
{
   signal(SIGUSR1, signal_callback_handler);
   signal(SIGUSR2, signal_callback_handler);

    printf("this line happned after signal arrived \n ");
   return EXIT_SUCCESS;
}
1 Answers

There are two possibilities:

  • pause() or
  • sigwait()

Documentation for pause:

Description
pause() causes the calling process (or thread) to sleep until a signal is delivered that either terminates the process or causes the invocation of a signal-catching function.

Source: https://linux.die.net/man/2/pause


And the documentation for sigwait:

Description
The sigwait() function suspends execution of the calling thread until one of the signals specified in the signal set set becomes pending. The function accepts the signal (removes it from the pending list of signals), and returns the signal number in sig.

Source: https://linux.die.net/man/3/sigwait

Both functions are conforming to POSIX.1-2001

Related