Windows equivalent for spawning and killing separate process group in Python 3?

谁说我不能喝 提交于 2020-01-15 07:29:13

问题


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

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)

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

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

I'm using Python 3.5.


回答1:


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

Here is what he said:

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()


来源:https://stackoverflow.com/questions/47016723/windows-equivalent-for-spawning-and-killing-separate-process-group-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!