Skip to content

Instantly share code, notes, and snippets.

@bogen
Last active August 29, 2015 14:22
Show Gist options
  • Save bogen/97acc31589aa631fa141 to your computer and use it in GitHub Desktop.
Save bogen/97acc31589aa631fa141 to your computer and use it in GitHub Desktop.
Python's signal handling with Gtk seems broken.... (not sure if it is Gtk/Gobject, or in the python binding for them)
#!/usr/bin/env python3
from gi.repository import Gtk, GObject
import signal, sys, os
count = {}
def signal_handler (signal, frame):
print('Signal %d trapped!' % signal)
if signal in count:
count [signal] += 1
else:
count [signal] = 1
signal.signal (signal.SIGINT, signal_handler)
signal.signal (signal.SIGQUIT, signal_handler)
signal.signal (signal.SIGTSTP, signal_handler)
signal.signal (signal.SIGUSR1, signal_handler)
print ("press any of the following multiple times:")
print ("\tCtrl-C")
print ("\tCtrl-\\")
print ("\tCtrl-Z")
print ("Also try 'kill -USR1 %d' from another terminal" % os.getpid ())
print ("Close window to exit program")
if len (sys.argv) > 1:
if sys.argv [1] == 't':
def on_timeout (user_data):
return True
GObject.timeout_add (50, on_timeout, on_timeout)
else:
print ("use '%s t' to start periodic timer" % sys.argv [0])
win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
print ('\nSummary:')
for i in count:
print ("\tSignal %d trapped %d times" % (i, count [i]))
When using Gtk3 and signal handlers set up with signal.signal,
the handlers are not run unless some other event is proccessed
by Gtk.main ()
Run the given python script with no arguments, and you will
see the faulty behavior. The summary shows that multiple
signal events are unaccounted for if they have to be handled
when the gtk window is closed.
Run the script with the 't' argument (no quotes) and you will
see that the signal handling is dependant on some other event
being handled that Gtk.main () knows what to do with.
Having to piggyback signal handlers on some other event
handling is a kludge. In the case of a long even timeout when
a timeout handler is being used to help the signal handler,
multiple signal events would still be lost.
@bogen
Copy link
Author

bogen commented Jun 12, 2015

@bogen
Copy link
Author

bogen commented Jun 12, 2015

https://developer.gnome.org/glib/stable/glib-UNIX-specific-utilities-and-integration.html#g-unix-signal-add

https://developer.gnome.org/glib/stable/glib-UNIX-specific-utilities-and-integration.html#g-unix-signal-source-new

"In GLib versions before 2.36, only SIGHUP, SIGINT, SIGTERM can be monitored. In GLib 2.36, SIGUSR1 and SIGUSR2 were added."

I did figure how how to use GLib.unix_signal_add from python, and it does not require a piggyback handler. However, the number of signals supported is limited.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment