Re: Handling Unix signals in a GTK+ application



On Saturday 11 March 2006 10:22, Gus Koppel wrote:
Thomas Okken wrote:
I would like to catch SIGINT in my GTK+ application,
to do a graceful exit. I was looking for the GTK+
equivalent of XtNoticeSignal(), but I guess there
isn't one; when I searched the archive, all I found
was some mention of a proposed GLib extension called
g_signal_notify() -- which looks like what I'm looking
for, but the thread in question is 6 years old and
nothing seems to have come of it.
I read a few articles discussing the use of a pipe,
with an input source to handle the "noticing the
event" bit within the main loop. It seems like a
kludge, but I suppose it's workable... Is this still
the recommended approach? (I notice the GTK
documentation is utterly silent on the whole topic.)

Yes, this is still the recommended way. GTK+ itself doesn't support
dealing with Unix signals at all. To handle them you need to use the
Unix libc functions. They are (mostly) standardized by POSIX for about
every Unix there is. Note that Windows and other completely different
architectures have nothing comparable to Unix signals.

The main problem is that you MUST NOT call any GTK+ or Glib function
within your signal handler. The signal may occur any time, not just when
your program sits waiting in the GTK+ main loop. It's a very bad
happening when any GTK+ functions are getting called from within a
signal handler while the program was just interrupted when being in the
middle of the execution of any other GTK+ function, i.e. opening a
dialog, drawing things or just allocating or freeing some memory.

So there's no direct way to inform the application about a Unix signal
has been triggered and handled. You just can't send a GTK+ signal from
within the Unix signal handler, for the reason stated above. Using a
Unix pipe which is being monitored by the GTK+ main loop is a proper way
to inform the application about the Unix signal being handled.

For a code example of how to deal with Unix signals in GTK+, see:
http://wwwtcs.inf.tu-dresden.de/~tews/Gtk/x2992.html

This is generally the best way of dealing with asynchronous (Unix) signals, 
but for simple cases another approach is just to set a flag of type volatile 
sig_atomic_t in the Unix signal handler, and then check and act on the status 
of the flag in the glib event loop with an idle handler set up with 
g_idle_add().

Chris




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]