Signal Handling in C

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

^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.

advertisement
advertisement
/* 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

^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

Note: Join free Sanfoundry classes at Telegram or Youtube
/* 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

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). 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!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.