-
signal
包的核心是使用signal.signal()
函数来预设(register)
信号处理函数,singnal.signal(signalnum, handler)
def spawn_visdom():
try:
subprocess.run(["visdom > visdom.txt 2>&1 &"], shell=True)
except:
print("Visdom is already running...")
def signal_handler(signal, frame):
subprocess.run(["pkill visdom"], shell=True)
print("Killing Visdom server...")
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
- 利用
alarm
制作一个超时器,该示例实现的功能是,为了防止打开一个文件出错或者其他异常一直处于等待的状态,设定一个定时器,5
秒后触发IOError
。如果5s
内正常打开文件,则清除定时器。
import signal, os
# 定义一个信号处理函数,该函数打印收到的信号,然后raise IOError
def handler(signum, frame):
print 'Signal handler called with signal', signum
raise IOError("Couldn't open device!")
# 对SIGALRM(终止)设置处理的handler, 然后设置定时器,5秒后触发SIGALRM信号
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
# This open() may hang indefinitely
fd = os.open('/dev/ttyS0', os.O_RDWR)
signal.alarm(0) # 关闭定时器