Search code examples
pythonsignals

Get pid of the process which has triggered some signal


Is it possible to find out the process id of the process which has caused some signal. In my scenario, I have multiple children of a process running, and I want to know which one of them sent the signal.


Solution

  • It is (finally!) very simple with python 3.

    The following is tested with python 3.3.3:

    #! /usr/bin/python3
    
    import signal
    import time, os
    
    def callme(num, frame):
        pass
    
    # register the callback:
    signal.signal(signal.SIGUSR1, callme)
    
    print("py: Hi, I'm %d, talk to me with 'kill -SIGUSR1 %d'"
          % (os.getpid(),os.getpid()))
    
    # wait for signal info:
    while True:
        siginfo = signal.sigwaitinfo({signal.SIGUSR1})
        print("py: got %d from %d by user %d\n" % (siginfo.si_signo,
                                                 siginfo.si_pid,
                                                 siginfo.si_uid))