Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect death of parent process

Tags:

c

linux

How can I detect parent process death in Linux OS?

If in parent process called fork(), that create child process. In the parent process I can use system call wait() for waiting terminated child process, and getting its status.

But, I can't find info about how child process can detect parent process' death?

like image 877
Simplex Avatar asked Aug 30 '12 09:08

Simplex


People also ask

What happens to a child process if the parent process is killed?

When a parent process dies before a child process, the kernel knows that it's not going to get a wait call, so instead it makes these processes "orphans" and puts them under the care of init (remember mother of all processes).

How do you check if a process has a parent?

Use getpid() and getppid() function to get process id and parent process id.

How do you check the process of a child process?

The pgrep and ps commands are useful in finding the direct child processes of a parent process. The pstree command lists all of the direct and indirect child processes in a tree structure. We can also find the child processes of a parent process in the /proc file system recursively.

What is the parent of a process?

In computing, a parent process is a process that has created one or more child processes.


1 Answers

You can get the parent process id by calling getppid() and then sending signal 0 via kill(). A return code of 0 will indicate that the process is still alive.

As mentioned by @Ariel, getppid() will either return the pid of the original parent or that of init, which will be pid 1. So you either have to store the parent pid by calling getppid() at startup or later check if your parent has pid 1.

According to this answer on Linux you can also detect the death of the parent via prctl()'s PR_SET_PDEATHSIG option and a self-chosen signal.

like image 138
scai Avatar answered Oct 02 '22 16:10

scai