Monday, 18 June 2012

Signal Handling in C

Signals are ways by which a process notify that some conditon(s) has/have occurred. For example divding by zero or segmentation fault are some of events that occurr and it is required to be notified by the process.

There are three ways to handle signals:

1. Ignore the signal, though this action is not recommended for signals related with hardware actions such as referncing memory outside address space of memory etc.

2. Let default action takes place.

3. Provide a function that gets called as soon as some signal occurrs. This kind of function is known as signal handler.

Note:  The signals SIGKILL and SIGSTOP cannot be caught or ignored.

If the signal signum is delivered to the process, then one of the following happens:

       *a* If the disposition is set to SIG_IGN, then the signal is ignored.

       *b*  If the disposition is set to SIG_DFL, then the default action associated with the signal (see signal(7)) occurs.

       *c*  If the disposition is set to a function, then first either the disposition is reset to SIG_DFL, or the signal is blocked and then handler is called with argument signum.  If invocation of the handler caused the  signal to be blocked, then the signal is unblocked upon return from the handler.


1. Ignoring the signal:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>


int main(int argc, char **argv)
{
        if(signal(SIGINT,SIG_IGN)==SIG_ERR)
        {
                perror("signal error");
        }
        while(1)
        {
                printf("\nHello!! You cant terminate me by pressing ctrl-C !! ;) \n");
         }
        return 0;
}


2. Handling the signal



#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>
int flag=0;
void sighandler(int signum)
{
        printf("\nSignal Handled ....\n Exiting...\n");
        flag=1;
}

int main(int argc, char **argv)
{
        if(signal(SIGINT,sighandler)==SIG_ERR)
        {
                perror("signal error");
        }
        while(flag!=1)
        {
                printf("\nHello!! Press ctrl-C to be caught by Handler!! ;) \n");
        //      sleep(1);
        }
        return 0;
}




3. If we dont state signal( ) function or write SIG_DFL instead of SIG_IGN then default action takes place.

0 comments

 
© 2011-2012 ProgrammingBlue
Posts RSS Comments RSS
Back to top