Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Howto launch a full process not a child process and retrieve the PID

I would like:

  1. Launch a new process (myexe.exe arg1) from my process (myexe.exe arg0)
  2. Retrieve the PID of this new process (os windows)
  3. when I kill my first entity (myexe.exe arg0) with the TaskManager Windows Command "End process tree", I need that the new one (myexe.exe arg1) will not be killed...

I've played with subprocess.Popen, os.exec, os.spawn, os.system... without success.

Another way to explain the problem: How to protect myexe.exe (arg1) if someone kills the "process tree" of the myexe.exe (arg0)?

EDIT: same question (without answer) HERE

EDIT: the following command do not guarantee the Independence of the subprocess

subprocess.Popen(["myexe.exe",arg[1]],creationflags = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP,close_fds = True)
like image 244
baco Avatar asked Feb 10 '13 11:02

baco


1 Answers

To start a child process that can continue to run after the parent process exits on 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 process creation flags are here

A more portable version is here.

like image 120
jfs Avatar answered Sep 21 '22 15:09

jfs