Python:如何启动完整进程而非子进程并获取PID
我想要做到以下几点:
- 从我的程序(myexe.exe arg0)启动一个新进程(myexe.exe arg1)
- 获取这个新进程的进程ID(PID),我使用的是Windows系统
- 当我通过Windows任务管理器的“结束进程树”命令杀掉第一个进程(myexe.exe arg0)时,我希望新进程(myexe.exe arg1)不会被一起杀掉...
我尝试过使用subprocess.Popen、os.exec、os.spawn、os.system等方法,但都没有成功。
换句话说,我想知道如果有人结束了myexe.exe(arg0)的“进程树”,我该如何保护myexe.exe(arg1)不被杀掉?
编辑:同样的问题(没有答案)可以在这里找到。
编辑:以下命令并不能保证子进程的独立性。
subprocess.Popen(["myexe.exe",arg[1]],creationflags = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP,close_fds = True)
4 个回答
1
所以如果我理解得没错,代码应该是这样写的:
from subprocess import Popen, PIPE
script = "C:\myexe.exe"
param = "-help"
DETACHED_PROCESS = 0x00000008
CREATE_NEW_PROCESS_GROUP = 0x00000200
pid = Popen([script, param], shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE,
creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
至少我试过这个,确实对我有效。
1
几年前我在Windows上做过类似的事情,我的问题是想要结束子进程。
我想你可以用 pid = Popen(["/bin/mycmd", "myarg"]).pid
来运行子进程,所以我不太确定真正的问题是什么,我猜是当你结束主进程的时候。
如果我没记错的话,这和一些标志有关。
我不能证明,因为我现在不在用Windows。
subprocess.CREATE_NEW_CONSOLE
The new process has a new console, instead of inheriting its parent’s console (the default).
This flag is always set when Popen is created with shell=True.
subprocess.CREATE_NEW_PROCESS_GROUP
A Popen creationflags parameter to specify that a new process group will be created. This flag is necessary for using os.kill() on the subprocess.
This flag is ignored if CREATE_NEW_CONSOLE is specified.
14
在Windows系统中,要启动一个子进程,使其在父进程退出后仍然可以继续运行:
from subprocess import Popen, PIPE
CREATE_NEW_PROCESS_GROUP = 0x00000200
DETACHED_PROCESS = 0x00000008
p = Popen(["myexe.exe", "arg1"], stdin=PIPE, stdout=PIPE, stderr=PIPE,
creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
print(p.pid)
关于Windows进程创建的标志,可以在这里找到详细信息。
还有一个更通用的版本在这里。