信号捕获在window上测试没有生效,在Linux上测试生效
1 import multiprocessing 2 import time 3 import signal 4 import os 5 import random 6 7 sid = 0 # 全局变量,进程之间的变量是否独立测试 8 9 def myhandler(signum, frame): 10 global sid 11 print(signum) 12 print(sid) 13 print("del del") 14 exit() 15 16 def test(): 17 global sid 18 signal.signal(signal.SIGTERM, myhandler) # 定义捕获信号和关闭时的处理函数 19 counter = 0 20 sid = random.randint(0,100) 21 while True: 22 print(counter, sid) 23 counter +=1 24 time.sleep(1) 25 26 27 if __name__=="__main__": 28 p = multiprocessing.Process(target=test) 29 p.start() 30 p1 = multiprocessing.Process(target=test) 31 p1.start() 32 p1.join(5) 33 if p1.is_alive(): 34 print(p1.pid) 35 print("Process Timeout, be Terminated !!!") 36 p1.terminate() # 发送关闭信号 37 p1.join() 38 p.terminate() 39 p.join() 40 print(sid)