我有这个听USR1信号的代码
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) print 'My PID is:', os.getpid() while True: print 'Waiting...' time.sleep(3)
当我用kill -USR1 pid
发送信号时,这是有效的
但是我怎样才能从上面的python脚本发送相同的信号,以便在10秒后它自动发送USR1
,并接收它,而不必打开两个terminal来检查它?
你可以使用os.kill() :
os.kill(os.getpid(), signal.SIGUSR1)
把它放在你想要发送信号的代码中的任何地方。
如果您愿意捕获SIGALRM
而不是SIGUSR1
,请尝试:
signal.alarm(10)
否则,你需要启动另一个线程:
import time, os, signal, threading pid = os.getpid() thread = threading.Thread( target=lambda: ( time.sleep(10), os.kill(pid, signal.SIGUSR1))) thread.start()
因此,这个程序:
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)
产生这个输出:
$ python /tmp/x.py My PID is: 3029 Waiting... Waiting... Waiting... Waiting... Received: 14 Waiting... Waiting...