Using the signal function, a signal interrupt, (SIGINT), is associated with a function called signalhandler1. That is, if the interrupt is autogenerated or is generated by the user, the sighandler1 function will be invoked. A counter, x, is initialized to 1 and a while loop is set to execute until the value of counter x becomes larger than 5. Within the while loop, the following text is displayed: Signal will be raised automatically after 5 seconds. In addition to this, the value of counter x is incremented by 1 within the while loop. A delay of 1 second is inserted in the while loop. In short, the while loop will display a text message after a gap of 1 second each. After displaying the text message 5 times, the raise function is invoked to raise the SIGINT signal.
On raising the SIGINT signal, the signalhandler1 function will be invoked. The signalhandler1 function does nothing other than display a text message: Ctrl+C is auto pressed. After executing the signalhandler1 function, the control resumes executing the statements in the main function. Again, the signal function is invoked and the SIGINT signal is associated with the sighandler2 function. Once more, a while loop is set to execute; however, this time, the loop will run indefinitely. Within the while loop, a text message, Infinite loop, press Ctrl+C to raise signal, is displayed. After displaying the text message, a delay of 1 second is inserted; that is, the text message will keep on displaying indefinitely after a gap of 1 second. If the user presses Ctrl + C, the signal interrupt will be raised and the sighandler2 function will be invoked.
In the sighandler2 function, a text message, You have pressed Ctrl+C, is displayed on one line and, on the next line, Press Ctrl+C again to exit is displayed. Thereafter, the signal function is invoked to set the SIGINT signal to take the default action. The default action of the SIGINT interrupt is to terminate and exit from the program. This means that if the user again presses Ctrl + C, the program will terminate.
The program is compiled using GCC, as shown in the following screenshot. Because no error appears during compilation, the signalhandling.c program has successfully compiled into a .exe file: signalhandling.exe. Upon executing this file, five text messages are displayed on the screen through the first while loop. After that, the signal is automatically raised and the text message from the first signal handler appears on the screen. Thereafter, a text message from the infinite while loop appears. Finally, the output from the second signal handler appears, which is executed when the signal interrupt is generated by the user. All of the actions appear as follows:
Voilà! We have successfully handled signals.