Windows 相当于在 Python 3 中生成和杀死单独的进程组? [英] Windows equivalent for spawning and killing separate process group in Python 3?

查看:30
本文介绍了Windows 相当于在 Python 3 中生成和杀死单独的进程组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 web 服务器需要管理一个单独的多进程子进程(即启动和终止它).

I have a web server that needs to manage a separate multi-process subprocess (i.e. starting it and killing it).

对于基于 Unix 的系统,以下工作正常:

For Unix-based systems, the following works fine:

# save the pid as `pid`
ps = subprocess.Popen(cmd, preexec_fn=os.setsid)

# elsewhere:
os.killpg(os.getpgid(pid), signal.SIGTERM)

我是这样做的(使用 os.setsid),否则杀死进度组也会杀死网络服务器.

I'm doing it this way (with os.setsid) because otherwise killing the progress group will also kill the web server.

在 Windows 上,这些 os 函数不可用——所以如果我想在 Windows 上完成类似的事情,我该怎么做?

On Windows these os functions are not available -- so if I wanted to accomplish something similar on Windows, how would I do this?

我使用的是 Python 3.5.

I'm using Python 3.5.

推荐答案

此答案由 eryksun 提供在评论中.我把它放在这里是为了突出它,因为有人可能也会卷入这个问题.

THIS ANSWER IS PROVIDED BY eryksun IN COMMENT. I PUT IT HERE TO HIGHLIGHT IT FOR SOMEONE MAY ALSO GET INVOLVED IN THIS PROBLEM

这是他说的:

您可以通过 ps = subprocess.Popen(cmd, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) 创建一个新的进程组.组 ID 是领导进程的进程 ID.也就是说,它只对树中与您的进程连接到同一控制台(conhost.exe 实例)的进程有用,如果您的进程甚至有一个控制台.在这种情况下,您可以通过 ps.send_signal(signal.CTRL_BREAK_EVENT) 向组发送 Ctrl+Break.进程不应忽略 Ctrl+Break.他们应该优雅地退出或让默认处理程序执行,它调用 ExitProcess(STATUS_CONTROL_C_EXIT)

You can create a new process group via ps = subprocess.Popen(cmd, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP). The group ID is the process ID of the lead process. That said, it's only useful for processes in the tree that are attached to the same console (conhost.exe instance) as your process, if your process even has a console. In this case, you can send the group a Ctrl+Break via ps.send_signal(signal.CTRL_BREAK_EVENT). Processes shouldn't ignore Ctrl+Break. They should either exit gracefully or let the default handler execute, which calls ExitProcess(STATUS_CONTROL_C_EXIT)

我用这个尝试并成功了:

I tried it with this and succeed:

process = Popen(args=shlex.split(command), shell=shell, cwd=cwd, stdout=PIPE, stderr=PIPE,creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
/*...*/
process .send_signal(signal.CTRL_BREAK_EVENT)
process .kill()

这篇关于Windows 相当于在 Python 3 中生成和杀死单独的进程组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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