加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

使用os.kill将SIGINT发送到Python子进程,就像按下Ctrl C一样

发布时间:2020-12-20 13:45:22 所属栏目:Python 来源:网络整理
导读:在 Windows上使用python 3.4. 我试图终止一个孩子处理模拟一个人按Ctrl C( Linux上的Ctrl D). 我刚刚添加了处理程序来检查信号是否正在被处理. I used the idea from this question 目标是捕获KeyboardInterrupt(SIGINT),并释放资源.但是,如果SIGINT不是来自
在 Windows上使用python 3.4.
我试图终止一个孩子处理模拟一个人按Ctrl C( Linux上的Ctrl D).

我刚刚添加了处理程序来检查信号是否正在被处理. I used the idea from this question

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

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:UsersRui>python test.py
[PID:16524] acquiring resources
<Process(Process-1,stopped[2])>
2
joined all processes

>我做错了什么?
>我应该使用子进程模块吗?
>我可以尝试其他哪些方法来中断流程执行?

解决方法

它不起作用,因为你不能使用os.kill在Windows上发送任意信号:

os.kill(pid,sig)

Send signal sig to the process pid. Constants for the specific signals
available on the host platform are defined in the signal module.

Windows: The signal.CTRL_C_EVENT and signal.CTRL_BREAK_EVENT signals
are special signals which can only be sent to console processes which
share a common console window,e.g.,some subprocesses. Any other
value for sig will cause the process to be unconditionally killed by
the TerminateProcess API,and the exit code will be set to sig
. The
Windows version of kill() additionally takes process handles to be
killed.

唯一可以通过os.kill发送的信号是signal.CTRL_C_EVENT和signal.CTRL_BREAK_EVENT.其他任何事情都会终止这个过程,这就是你的情况.使用signal.CTRL_C_EVENT也不会在这里工作,因为通过multiprocessing.Process启动的进程不是与父进程共享公共控制台窗口的“控制台进程”.我不确定你能在这里用Windows上的信号做多少事情;看起来你不能像在Unix上捕获SIGTERM那样捕获TerminateProcess,因此在进程终止之前你不能进行任何清理工作,并且你没有为子进程使用控制台应用程序,所以信号.* _ EVENT不起作用.

我认为您的选择是:1)使用子进程模块,并使用shell = True启动子进程,我相信这意味着signal.CTRL C EVENT将起作用. 2)坚持使用多处理模块,并使用“合作”方法来中断工作人员,如multiprocessing.Event.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读