Unofficial Appendix. Catching Unix signals

Note

This section was written in spring 2005 as a contribution to the GTK tutorial. I even submitted the SGML sources to the maintainer of the GTK tutorial, Tony Gale. I can't recall if I got an answer. In any case, it was not included in the GTK tutorial. The few answers that I got on the GTK mailing lists were just misleading and ignorant, see here and here.

This chapter describes how to catch and respond to Unix-signals in GTK applications. Unix-signals are completely unrelated to GTK's signals. Outside the GTK world Unix-signals are just called signals, but here I stick with the longer term to avoid confusion.

1. Short Introduction into Unix-signals

Unix-signals are a mechanism to asynchronously notify a running application about certain external events. For instance, pressing Crtl-C on the controlling terminal usually results in sending the Unix-signal SIGINT to the application. For SIGINT the default action is to terminate the receiving application.

The set of distinct Unix-signals varies among the different Unixes. Posix requires 19 Unix-signals, currently Linux implements 64. For most of the Unix-signals the application can decide, whether

For the first and the third option it is pretty clear what happens. If the application decides to handle the Unix-signal it must specify a function as Unix-signal handler. On receipt of the Unix-signal the operating system stops the current activity of the application and lets the Unix-signal handler run. After its termination the application continues.

Why would one choose to handle a signal? It is certainly not a good idea to ignore SIGINT. After all, people hit Ctrl-C to terminate the application, so SIGINT should (eventually) terminate the application. However, by handling SIGINT the application can terminate gracefully. For instance on SIGINT the application might write out a data base or release some locks before it terminates.

In the Unix-signal handler one can only use a certain (small) set of save functions (see man signal). Unfortunately the functions from the GTK, GDK, and also the GObj libraries do not belong to these save functions. Therefore one usually has to use special techniques (described in the next section) to propagate the information about the Unix-signals from the handler to the rest of the application.

Note

From the application's point of view the Unix-signal handling function runs completely asynchronously (it could happen in the middle of an assignment). If the handler communicates with the rest of the program via shared variables, those variables have to be declared volatile. Otherwise the application might not notice the changes. Moreover the handler and the rest of the application should not modify the same variables. Otherwise you might loose changes or corrupt the variables.

There is much more to say about signals. See the documentation in the manual pages signal(2) and signal(7).