[Python] Python spawn off a child subprocess, detach, and exit

Discussão em 'Python' iniciado por Stack, Março 17, 2025.

  1. Stack

    Stack Membro Participativo

    I'm wondering if this is the correct way to execute a system process and detach from parent, though allowing the parent to exit without creating a zombie and/or killing the child process. I'm currently using the subprocess module and doing this...

    os.setsid()
    os.umask(0)
    p = subprocess.Popen(['nc', '-l', '8888'],
    cwd=self.home,
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT)


    os.setsid() changes the process group, which I believe is what lets the process continue running when it's parent exits, as it no longer belongs to the same process group.

    Is this correct and also is this a reliable way of performing this?

    Basically, I have a remote control utility that communicate through sockets and allows to start processes remotely, but I have to ensure that if the remote control dies, the processes it started continue running unaffected.

    I was reading about double-forks and not sure if this is necessary and/or subprocess.POpen close_fds somehow takes care of that and all that's needed is to change the process group?

    Continue reading...

Compartilhe esta Página