在Python 多进程中使用signal,pythonsignal,下面的代码我只在基于ub


下面的代码我只在基于ubuntu的deepin12.06(Linux zzh 3.2.0-32-generic #51-Ubuntu SMP Wed Sep 26 21:32:50 UTC 2012 i686 athlon i386 GNU/Linux)上测试过,由于signal是一个操作系统特性,所以不保证其他系统可行

signal 接受信号

import signalimport osimport timedef receive_signal(signum, stack):    print 'Received:', signum# Register signal handlerssignal.signal(signal.SIGUSR1, receive_signal)signal.signal(signal.SIGUSR2, receive_signal)# Print the process ID so it can be used with 'kill'# to send this program signals.print 'My PID is:', os.getpid()while True:    print 'Waiting...'    time.sleep(3)

传递信号可以在shell中操作一些命令

kill -USR1 $pidkill -USR2 $pidkill -INT $pid

signal 获取注册的处理函数

#SIG_ING 如果信号被忽略#SIG_DFL 如果使用默认行为#None from Cimport signaldef alarm_received(n, stack):    returnsignal.signal(signal.SIGALRM, alarm_received)signals_to_names = dict(    (getattr(signal, n), n)    for n in dir(signal)    if n.startswith('SIG') and '_' not in n    )for s, name in sorted(signals_to_names.items()):    handler = signal.getsignal(s)    if handler is signal.SIG_DFL:        handler = 'SIG_DFL'    elif handler is signal.SIG_IGN:        handler = 'SIG_IGN'    print '%-10s (%2d):' % (name, s), handlersignal 发送信号    使用os.kill()可以发送信号,前面有介绍signal 闹钟#2秒就after了import signalimport timedef receive_alarm(signum, stack):    print 'Alarm :', time.ctime()# Call receive_alarm in 2 secondssignal.signal(signal.SIGALRM, receive_alarm)signal.alarm(2)print 'Before:', time.ctime()time.sleep(4)print 'After :', time.ctime()signal 忽略信号import signalimport osimport timedef do_exit(sig, stack):    raise SystemExit('Exiting')signal.signal(signal.SIGINT, signal.SIG_IGN)signal.signal(signal.SIGUSR1, do_exit)print 'My PID:', os.getpid()signal.pause()#当接受到键盘的时候,signal.SIG_IGN给忽略了

signal 与线程

signal一般不能跟线程很好的合作,因为操作系统的特性,只能主线程接收得到信号,关于这个,以后再研究:

评论关闭