2013-02-26 130 views
14

我有這樣的代碼,它會監聽USR1信號如何從python程序發送信號?

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也收到它,我不必打開兩個終端來檢查它?

回答

5

如果你願意搭上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... 
+0

我在哪裏需要將該行放在我的上述腳本中 – user192082107 2013-02-26 03:20:16

+0

在您想要10秒鐘啓動的時刻,將這些代碼片段中的任意一個放入腳本中。例如,你可以把它放在'while'之前。 – 2013-02-26 03:24:50

+0

我不想發送報警信號,只有'USR1',你可以在我當前的腳本中給出這個例子 – user192082107 2013-02-26 03:52:59

24

您可以使用os.kill()

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

把你的代碼,這在任何地方,你想從發送信號。