Monday, November 12, 2012

Signal handling in Linux using signal() call

signal() function in linux is used to sets of handler for the given signal number, the handler is any of SIG_DFL(default action) or SIG_IGN(ignore signal) or address of user defined function which we called signal handler

syntax:
         sighandler_t signal(int signum, sighandler_t handler);

the second parameter is the address of the signal handler function (function pointer), which has the following syntax

         typedef void (*sighandler_t)(int );

Here the parameter int represents the Signal number.

Here is the simple C program which describes the SIGINT Signal handling in linux

signal.c

#include<stdio.h>
#include<signal.h>
void sig_handler(int signum)
{
    printf("I'm in INT_SIGNAL handler:%d\n",signum);
}


int main()
{
    signal(SIGINT,sig_handler);

    while(1)
    {
        printf("hello i'm in main\n");
        sleep(1);
    }

    return 0;
}


Output:
$gcc -o signal signal.c
$./signal
hello i'm in main
hello i'm in main
^CI'm in INT_SIGNAL handler:2
hello i'm in main
hello i'm in main
hello i'm in main
^CI'm in INT_SIGNAL handler:2
hello i'm in main
hello i'm in main
^Z
[2]+ Stopped ./signal

Note: to send the SIGINT signal to the process, use shortcut key CTRL+c in the keyboard while program being executed, then our handler will invoked. To stop the program press CTRL+z keys.

Note: to see list of signals in linux system open terminal, then enter the command
               $kill -l

2 comments: