Answer: As we know that when program executes performs certain actions, for ex. requesting for input, open some file for read operation, etc. There are events that the program must reach to but these aren’t caused by the program, for ex. interrupts to a program etc. We can’t predict when such events occur. In order to avoid partially computed results from being lost, program must be arranged to handle such events. Signals are used for this purpose.
A signal occurs asynchronously that is it’s not synchronised with any thing in the program’s execution. When a program isn’t prepared to handle a specific signal, default action is implemented. Signals are asynchronous and synchronous. Synchronous signals are those which are caused from within the program. For ex. SIGSEGV, SIGILL, SIGABRT etc.
SIGABRT signal is raised by ‘abort()’ function to abnormally terminate the program. SIGSEGV signal occurs when program attempts to access an invalid memory reference. Similarly, SIGILL signal occurs when processor attempts to execute some illegal instruction.
Asynchronous signals occur from outside that is by program’s user to tell something to program. For example, SIGINT and SIGTERM signals are asynchronous signals. SIGINT occurs when user attempts to interrupt the executing program while SIGTERM signal occurs when implementation requests the program should be terminated.
Let’s consider a C program that raises SIGINT signal and handles it.
/* signal_ctrlC.c -- program handles interrupt 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; }
Observe the output below
^C : got ctrl-C signal handled! ^C : got ctrl-C signal handled! ^C : got ctrl-C signal handled!
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Watch Advanced C Programming Videos
- Apply for Computer Science Internship
- Practice Computer Science MCQs
- Check Computer Science Books
- Apply for C Internship