Evan Fosmark
Evan Fosmark

Reputation: 101661

Child process detecting the parent process' death in Python

Is there a way for a child process in Python to detect if the parent process has died?

Upvotes: 13

Views: 7174

Answers (4)

Giampaolo Rodolà
Giampaolo Rodolà

Reputation: 13056

Assuming the parent is alive when you start to do this, you can check whether it is still alive in a busy loop as such, by using psutil:

import psutil, os, time
me = psutil.Process(os.getpid())
while 1:
    if me.parent() is not None:
        # still alive
        time.sleep(0.1)
        continue
    else:
        print("my parent is gone")
        break

Not very nice but...

Upvotes: 5

Ringding
Ringding

Reputation: 2856

The only reliable way I know of is to create a pipe specifically for this purpose. The child will have to repeatedly attempt to read from the pipe, preferably in a non-blocking fashion, or using select. It will get an error when the pipe does not exist anymore (presumably because of the parent's death).

Upvotes: 3

Alnitak
Alnitak

Reputation: 339786

If your Python process is running under Linux, and the prctl() system call is exposed, you can use the answer here.

This can cause a signal to be sent to the child when the parent process dies.

Upvotes: 5

unwind
unwind

Reputation: 399793

You might get away with reading your parent process' ID very early in your process, and then checking, but of course that is prone to race conditions. The parent that did the spawn might have died immediately, and even before your process got to execute its first instruction.

Unless you have a way of verifying if a given PID refers to the "expected" parent, I think it's hard to do reliably.

Upvotes: 1

Related Questions