我有这样的代码,它会监听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
并且还接收它,而我需要打开两个终端来检查呢?
您可以使用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...