Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a child process wait for the parent process to terminate in Linux programming in C?

Tags:

c

linux

unix

In C programming for Linux, I know the wait() function is used to wait for the child process to terminate, but are there some ways (or functions) for child processes to wait for parent process to terminate?

like image 839
python3 Avatar asked Sep 22 '15 17:09

python3


2 Answers

Linux has an extension (as in, non-POSIX functions) for this. Look up prctl ("process-related control").

With prctl, you can arrange for the child to get a signal when the parent dies. Look for the PR_SET_PDEATHSIG operation code used with prctl.

For instance, if you set it to the SIGKILL signal, it effectively gives us a way to have the children die when a parent dies. But of course, the signal can be something that the child can catch.

prctl can do all kinds of other things. It's like an ioctl whose target is the process itself: a "process ioctl".

like image 137
Kaz Avatar answered Oct 01 '22 12:10

Kaz


Short answer: no.

A parent process can control the terminal or process group of its children, which is why we have the wait() and waitpid() functions. A child doesn't have that kind of control over its parent, so there's nothing built in for that.

If you really need a child to know when its parent exits, you can have the parent send a signal to the child in an atexit() handler, and have the child catch that signal.

like image 41
dbush Avatar answered Oct 01 '22 14:10

dbush