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
/* 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
Related Posts:
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Practice BCA MCQs
- Apply for C Internship
- Watch Advanced C Programming Videos