gpt4 book ai didi

python - python 中 subprocess.Popen preexec_fn 和 start_new_session 之间的区别

转载 作者:行者123 更新时间:2023-12-02 02:34:46 27 4
gpt4 key购买 nike

Linux下使用subprocess.Popenpython3.2+启动新进程的这两个选项有什么区别:

proc = subprocess.Popen(args, ..., preexec_fn=os.setsid)   # 1
proc = subprocess.Popen(args, ..., start_new_session=True) # 2

我需要这个,因为我需要设置进程组 ID 才能立即终止该进程及其所有子进程。如果进程运行时间超过特定阈值,则使用此方法:

try:
out, err = proc.communicate(timeout=time_max)
except subprocess.TimeoutExpired:
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)

我使用这两个选项(#1#2)测试了我的代码,它们似乎都适合我。

但我想知道这里最好的选择是什么 - 带有 preexec_fn 的选项还是带有 start_new_session 的选项?

最佳答案

据官方Python Docs ,

The preexec_fn parameter is not safe to use in the presence of threads in your application. The child process could deadlock before exec is called. If you must use it, keep it trivial! Minimize the number of libraries you call into.

If you need to modify the environment for the child use the env parameter rather than doing it in a preexec_fn. The start_new_session parameter can take the place of a previously common use of preexec_fn to call os.setsid() in the child.

所以我想你问题的答案是 start_new_session引入来替代使用 preexec_fn 的常见操作通过os.setsid()设置 session id ,这不是线程安全的。

关于python - python 中 subprocess.Popen preexec_fn 和 start_new_session 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42257512/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com