What are Different Ways in Which Signals are Handled

«
»
Question: What are Different Ways in Which Signals are Handled?

Answer: There are three ways defined in which signals are managed. Default way is implementation dependent. Often this is defined to abort the program. SIG_DFL performs the default action for the specified signal. For ex., program terminates when user interrupts the executing program. For example,

/* sigint.c -- program implements default action to interrupt */
/* (ctrl-C) by the user */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
 
int main(void)
{
    /* ctrl-C raises SIGINT signal */
    signal(SIGINT, SIG_DFL);
 
    while (1)
        /* spinning here waiting for ctrl-C */
 
    return 0;
}

Output as follows

advertisement
^C

Of other ways, call a signal function either to ignore the signal or install a handler to manage signal. Let’s take an example for each of two cases.

/* sigint_ign.c -- program ignores interrupt (ctrl-C) by the user */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
 
int main(void)
{
    signal(SIGINT, SIG_IGN);
    while (1)
        /* spinning here waiting for ctrl-C */
       ;
 
    return 0;
}

Output as follows

advertisement
^C
^C
^C
^C

Now, turn ours’ attention to install ‘handler()’ function which is called when signal, for which handler is defined, is raised. Let’s consider a simple C program below

/* sigint.c -- program handles interrupt (ctrl-C) by the user */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
 
void handler(int signal)
{
    if (signal == SIGINT)
        printf(" : got ctrl-C signal handled!\n");
}
 
int main(void)
{
    signal(SIGINT, handler);
    while (1) {
        /* spinning here waiting for ctrl-C */
    }
 
    return 0;
}

Output is as follows

advertisement
^C : got ctrl-C signal handled!
^C : got ctrl-C signal handled!

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn