Using Signals to Handle Asynchronous Events

You can use signals to handle asynchronous user events. A process (program code) can send a signal to itself that can be handled asynchronously based on the signal handler registered for it. This provides a way to perform tasks in parallel without any complex thread manipulation in the program code.

The following example code demonstrates how a program code sets a signal to itself and how it handles the signal asynchronously in a signal handler:

#include <signal.h>
#include <stdio.h>
void sighandler(int signum)
    {
    if(signum == SIGUSR1)
        {
        // Code to perform custom handling
        }
    else if(signum == SIGUSR2)
        {
        // Code to perform custom handling
        }
    }
int main()
    {
    signal(SIGUSR1,sighandler);
    signal(SIGUSR2,sighandler);
    // program logic
    raise(SIGUSR1); // indicates user event one
    // program logic
    raise(SIGUSR2); // indicates user event two
    // program logic
    return 0;
    }