python中subprocess.Popen preexec_fn和start_new_session之间的区别 [英] Difference between subprocess.Popen preexec_fn and start_new_session in python

查看:668
本文介绍了python中subprocess.Popen preexec_fn和start_new_session之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个选项之间的区别是什么,对于Linux下的python3.2+subprocess.Popen启动新进程:

What is the difference between these two options to start a new process with subprocess.Popen for python3.2+ under Linux:

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

我需要这个,因为我需要设置进程组ID,以便有可能立即杀死该进程及其所有子进程.然后,如果流程运行时间超过特定阈值,则使用此方法:

I need this as I need to set process group ID to have a possibility to kill at once this process and all of its children. This is then used in the case if the process run time exceeds certain threshold:

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

我使用两个选项(#1#2)测试了我的代码,它们对我来说似乎都可以正常工作.

I tested my code with the both options (#1 & #2) and they both seem to work ok for me.

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

But I wonder what is the best option here - the one with preexec_fn or the one with start_new_session?

推荐答案

根据官方 Python文档

在应用程序中存在线程的情况下,不安全使用preexec_fn参数.子进程可能在调用exec之前死锁.如果您必须使用它,请保持琐碎!最小化您要调用的库的数量.

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.

如果您需要为子级修改环境,请使用env参数,而不要在preexec_fn中使用它. start_new_session参数可以代替之前在孩子中调用os.setsid()的preexec_fn的常用用法.

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()设置会话ID的常见操作,这不是线程安全的.

So I guess the answer to your question is that start_new_session was introduced to replace the common operation of using preexec_fn to set the session id through os.setsid(), which is not thread safe.

这篇关于python中subprocess.Popen preexec_fn和start_new_session之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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