This signal is generated when a user type control-C in a console. It can also be generated by the kill command. The intention of this signal is “suggest the process to exit”. In other words, the default signal disposition is to terminate the process. However, this signal can be intercepted or even ignored.
Many programs change the default disposition of SIGINT. However, ignoring a user’s request to quit a program is also not appropriate. Most programs changes the disposition so that a program has a chance to shut down properly, then quit.
If a program is to intercept SIGINT to shut down gracefully, it should use the following strategy:
To save the old handler and set up a new handler:
Then, the signal handler handleInt should be structured as follows:
The following is a complete program to test the handling of SIGINT:
If sigaction is not called in the handler, but raise is kept, then the program will endlessly and “recursively” raise the signal, handle it, and raise the signal again. This will, eventually run out of stack space.
If sigaction is put in place, but the raise call is removed, then the first control-C will only cause the message to be printed, but the handler will return and continue the infinite loop in main. When control-C is pressed again, then the program will exit by the default handler of SIGINT.
An alternative (to the original code in the listing) is to use the SA_RESETHAND value in sa_flags. This flag instructs the system to restore the default handler once a signal handler is called. In this case, this flag (use it when newSigAction.sa_flags is initialized) would have accomplished the same logic, and the sigaction call in the handler is no longer needed.