Detect user logout / shutdown in Python / GTK under Linux - SIGTERM/HUP not received

前端 未结 2 1526
遥遥无期
遥遥无期 2021-01-18 00:04

OK this is presumably a hard one, I\'ve got an pyGTK application that has random crashes due to X Window errors that I can\'t catch/control.

So I created a wrapper t

相关标签:
2条回答
  • 2021-01-18 00:36

    You forgot to close gtk's event loop.

    This code exits with code 0 when you close the window:

    import gtk
    
    class Test(gtk.Window):
        def destroy_event(self, widget, data=None):
            gtk.main_quit()
    
        def __init__(self):
            gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
            self.connect("destroy", self.destroy_event)
            self.show()
    
    f = Test()
    gtk.main()
    

    EDIT: Here's the code to catch the SIGTERM signal:

    import signal
    
    def handler(signum, frame):
        print 'Signal handler called with signal', signum
        print 'Finalizing main loop'
        gtk.main_quit()
    
    signal.signal(signal.SIGTERM, handler)
    

    The rest of the code is exactly as above, no changes. It works here when I send SIGTERM to the python process: gtk main loop ends and program exits with exit code 0.

    0 讨论(0)
  • 2021-01-18 00:54

    OK, I finally found the solution :)

    You simply can't rely on signals in this case. You have to connect to the Desktop Session in order to get notified that a logout is going to happen.

    import gnome.ui
    
    gnome.program_init('Program', self.version) # This is going to trigger a warning that program name has been set twice, you can ignore this, it seems to be a problem with a recent version of glib, the warning is all over the place out there
    client = gnome.ui.master_client() # connect us to gnome session manager, we need to init the program before this
    client.connect('save-yourself', self.on_logout) # This gets called when the user confirms the logout/shutdown
    client.connect('shutdown-cancelled', self.on_logout_cancel) # This gets called when the logout/shutdown is canceled
    client.connect('die', self.on_logout) # Don't know when this gets called it never got in my tests
    
    def on_logout(self, *args):
        # save settings an create a file that tells the wrapper that we have exited correctly!
        # we'll still return with status code 1, but that's just gtk crashing somehow
    
    def on_logout_cancel(self, *args):
        # simply delete the logout file if it exists
    

    One important note here: Don't try to exit your program in on_logout, if you do so, GNOME won't recognize that your program has been exited and will give you the dialog that some programs are still running.

    0 讨论(0)
提交回复
热议问题