Parent and child processes, how to notify the other to exit if one exits?
If I spawn a process in my linux C program and there are 2 processes in total, one parent and one child. I thought: if one of these two processes exits, the other process also exits.
How to achieve this?
Is there a similar source code?
Note: I don’t want to
block both processes at the same time, for example, I don’t want the parent process to be blocked by wait().
Thanks!
Solution
In the parent process, you can use >waitpid system calls. It blocks until child exits.
You cannot use waitpid
in child processes. ONE OPTION IS FOR THE FATHER TO NOTIFY THE CHILD BY SENDING A SIGTERM
TO THE CHILD WHEN HE EXITS. BUT THIS ONLY WORKS IF THE FATHER WILL NOT BE KILLED BY SIGKILL
. I recommend using kill
with parameter 0
to periodically signal the parent process. If it fails, the process terminates.
fromkill(2) man page :
if sig is 0, then no signal is sent, but error checking is still performed; this can be used to check for the existence of a process ID or process group ID.