使用os.kill将SIGINT发送到Python子进程,就像按Ctrl + C一样 [英] Send SIGINT to Python subprocess using os.kill as if pressing Ctrl+C

查看:187
本文介绍了使用os.kill将SIGINT发送到Python子进程,就像按Ctrl + C一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows上使用python 3.4.
我试图终止模拟Ctrl + C(在Linux上为Ctrl + D)的人的子进程.

Using python 3.4 on windows.
I am trying to terminate a child processing simulating a person pressing Ctrl+C (Ctrl+D on linux).

我刚刚添加了处理程序,以检查信号是否已被处理. 我使用了这个问题的想法

I just added the handler to check if the signal was being handled at all. I used the idea from this question

目标是捕获KeyboardInterrupt(SIGINT),并释放资源.但是,如果SIGINT不是来自键盘,则似乎不会引发异常.这就是为什么我创建了一个处理程序,但是该进程似乎根本没有运行该处理程序的原因...

The objective is to catch the KeyboardInterrupt (SIGINT), and release the resources. But it seems that the exception is not thrown if SIGINT doesnt come from the keyboard. That's why I created an handler, but the process doesnt seem to run the handler at all...

import multiprocessing
import time
import signal
import signal
import os
import sys

def handler(signal, frame):
    print("handler!!!")
    sys.exit(10)

def worker(): 
    p = multiprocessing.current_process()
    try:
        signal.signal(signal.SIGINT,handler)  
        print("[PID:{}] acquiring resources".format(p.pid))
        while(True):           
            #working...
            time.sleep(0.5)
    except (KeyboardInterrupt, SystemExit):
        pass
    finally:
        print("[PID:{}] releasing resources".format(p.pid))

if __name__ == "__main__":
    lst = []
    for i in range(1):
        p = multiprocessing.Process(target=worker)
        p.start()
        lst.append(p)

    time.sleep(3)      
    for p in lst:        
        os.kill(p.pid,signal.SIGINT)
        p.join()
        print(p)
        print(p.exitcode)
    print("joined all processes")

以下是输出示例:

C:\Users\Rui>python test.py
[PID:16524] acquiring resources
<Process(Process-1, stopped[2])>
2
joined all processes

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆