17

我想:

  1. 从我的进程 (myexe.exe arg0) 启动一个新进程 (myexe.exe arg1)
  2. 检索这个新进程的 PID(操作系统窗口)
  3. 当我使用 TaskManager 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

3 回答 3

12

在 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 进程创建标志在这里

更便携的版本在这里

于 2013-02-10T11:53:35.093 回答
1

几年前我在 Windows 上做过类似的事情,我的问题是想杀死子进程。

我想你可以运行子pid = Popen(["/bin/mycmd", "myarg"]).pid 进程,所以我不确定真正的问题是什么,所以我猜是你杀死主进程的时候。

IIRC 这与旗帜有关。

我无法证明这一点,因为我没有运行 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.
于 2013-02-10T11:36:36.153 回答
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)

至少我试过这个并为我工作。

于 2015-02-18T19:01:32.410 回答