How can I send a signal from a python program?

前端 未结 2 1029
眼角桃花
眼角桃花 2020-12-05 13:45

I have this code which listens to USR1 signals

import signal
import os
import time

def receive_signal(signum, stack):
    print \'Received:\', signum

signa         


        
相关标签:
2条回答
  • 2020-12-05 14:26

    You can use os.kill():

    os.kill(os.getpid(), signal.SIGUSR1)
    

    Put this anywhere in your code that you want to send the signal from.

    0 讨论(0)
  • 2020-12-05 14:43

    If you are willing to catch SIGALRM instead of SIGUSR1, try:

    signal.alarm(10)
    

    Otherwise, you'll need to start another thread:

    import time, os, signal, threading
    pid = os.getpid()
    thread = threading.Thread(
      target=lambda: (
        time.sleep(10),
        os.kill(pid, signal.SIGUSR1)))
    thread.start()
    

    Thus, this program:

    import signal
    import os
    import time
    
    def receive_signal(signum, stack):
        print 'Received:', signum
    
    signal.signal(signal.SIGUSR1, receive_signal)
    signal.signal(signal.SIGUSR2, receive_signal)
    signal.signal(signal.SIGALRM, receive_signal)  # <-- THIS LINE ADDED
    
    print 'My PID is:', os.getpid()
    
    signal.alarm(10)                               # <-- THIS LINE ADDED
    
    while True:
        print 'Waiting...'
        time.sleep(3)
    

    produces this output:

    $ python /tmp/x.py 
    My PID is: 3029
    Waiting...
    Waiting...
    Waiting...
    Waiting...
    Received: 14
    Waiting...
    Waiting...
    
    0 讨论(0)
提交回复
热议问题