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
Take C Programming Tests Now!
/* 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
Next Steps:
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Watch Advanced C Programming Videos
- Practice BCA MCQs
- Apply for C Internship
- Apply for Computer Science Internship
- Buy Computer Science Books