Search code examples
pythonsubprocesspipereconnect

Can python subprocess pipe reattach to original child process when program restart?


I am looking for a safe way to restart my python program that is able to regain control of the child process launched before restart.

I use subprocess with thread to monitor the stdout/stderr of a long run command which will continuously generate some output message.

The sample code snippet is as follow:

class PS(threading.Thread):
    def __init__(self, command):
        threading.Thread.__init__(self)
        self.command = command

    def run(self):
        try:
            process = subprocess.Popen(self.command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            for line in iter(process.stdout.readline, ''):
                ''' do something to line'''

When my python main program is terminated (kill its pid for example), its child process (the command executed by the PS class) is still alive as a background process.

My question is, is there any way in python to "reattach" the child process so that I can keep monitoring its stdout/stderr?

P.S. I only need it in linux environment, more specifically in ubuntu 14.04.


Solution

  • When the standard output of the child is tied to a pipe, the child will receive a SIGPIPE signal if it tries to write to that pipe after the parent dies, since the remote end of the pipe no longer exists.

    To ensure the child survives the parent, and to allow the parent to resume, you should simply write to a file and have the parent read from that file instead.