How to keep child process active when parent is killed/finished (in windows)

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

In Windows, by default, child processes are terminated when the parent process is killed or finishes execution. However, if you want to keep a child process active even after the parent process is terminated, you can achieve that using process detachment. One way to do this is by using the CREATE_NEW_PROCESS_GROUP flag when creating the child process. Here's an example in Python:

python
import subprocess
import os

# Command to execute as the child process
command = ["your_child_process.exe"]

# Create a new process group
creation_flags = subprocess.CREATE_NEW_PROCESS_GROUP

# Start the child process
child_process = subprocess.Popen(command, creationflags=creation_flags)

# Detach the child process from the parent process
child_pid = child_process.pid
if os.name == "nt":
import ctypes
ctypes.windll.kernel32.DetachConsole()

# Exit the parent process

In this example, replace "your_child_process.exe" with the actual command or executable you want to run as the child process. The CREATE_NEW_PROCESS_GROUP flag is used in the subprocess.Popen call to create a new process group for the child process. This allows the child process to continue running even after the parent process exits.

After starting the child process, the parent process detaches itself from the console using the DetachConsole function from the ctypes module. This step is specific to Windows and ensures that the child process remains unaffected when the parent process exits.

Once the parent process exits, the child process will continue running independently. Note that the child process will inherit its standard input, output, and error from the parent process unless you explicitly redirect them or detach the child process from the console.

Please note that detaching a child process from the parent process can have implications on system resource management. Ensure that you handle the child process appropriately and manage any necessary cleanup or termination.