How to implement signal handler for a process in linux

How to implement signal handler for a process in linux

Signals are types of interrupts that are generated from the kernel, and are very useful for handling asynchronous events. A signal-handling function is registered with the kernel, and can be invoked asynchronously from the rest of the program when the signal is delivered to the user process.



In the below example, signal handler (which is the call back function) is passed to the API "signal" / signal handler is registered with the Kernel, using Function pointer. So, when the kernel receives a particular signal, then it invokes this call back function whose code gets executed then. Basically, the signal handler is passed into signal API from a user space process, but this signal handler code is executed by Kernel, when the Kernel receives that signal.   


 

/ * This code catches the alarm signal generated from the kernel



    Asynchronously */


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

void sig_handler(int signo)
{
    if (signo == SIGUSR1)
        printf("received SIGUSR1\n");
    else if (signo == SIGKILL)
        printf("received SIGKILL\n");
    else if (signo == SIGSTOP)
        printf("received SIGSTOP\n");
}

int main(void)
{    /* register signal handler */
    if (signal(SIGUSR1, sig_handler) == SIG_ERR)
        printf("\ncan't catch SIGUSR1\n");
    if (signal(SIGKILL, sig_handler) == SIG_ERR)
        printf("\ncan't catch SIGKILL\n");
    if (signal(SIGSTOP, sig_handler) == SIG_ERR)
        printf("\ncan't catch SIGSTOP\n");
    // A long long wait so that we can easily issue a signal to this process. So, wait for the signal to be received from the kernel.
    while(1)
        sleep(1);
    return 0;
}
Output :
$ ./sigfunc

can't catch SIGKILL

can't catch SIGSTOP