ensuring child processes are terminated if parent crashes

This is the place for queries that don't fit in any of the other categories.

ensuring child processes are terminated if parent crashes

Postby dbrb2 » Sun Feb 02, 2014 2:52 pm

Hi,

I have a python script running on Linux that needs to send out periodic heartbeats for ever so long as the parent is active, to another system
To accomplish this, I have used the multiprocessing module:
Code: Select all
parent_pid=os.getppid()
heart = Process(target=heartbeat,args=parent_pid)
heart.start()

Where the heatbeat function is an infinite loop sending occasional heartbeats

Assuming the parent exits normally, this process is killed. If the parent crashes for whatever reason though, I have found that the child process can be left sending heartbeats, which is a problem

My attempt to solve this has been to capture the parent pid:
Code: Select all
parent_pid=os.getppid()

which I then pass to the child

The child then periodically calls:
Code: Select all
os.kill(parent_pid, 0):


Which should throw an exception (and do nothing) if the process does not exist, allowing me to check that the parent is still running. If not, then it terminates itself

Should this work OK, and is there a more elegant solution I am missing...?
dbrb2
 
Posts: 1
Joined: Sun Feb 02, 2014 2:46 pm

Return to General Coding Help

Who is online

Users browsing this forum: micseydel and 5 guests