3

If I spawn a process in my linux C program and there are 2 processes in total, a parent process and a child process. I want: if one of these 2 processes exits, the other process also exits.

How to achieve this? are there any similar source codes?

Note: I don't want to block both processes, e.g, I don't want the parent process to be blocked by wait()

thanks!

user1944267
  • 1,557
  • 5
  • 20
  • 27

4 Answers4

4

In father process you can use the waitpid system call. It will block until the child exits.

In the child process you cannot use waitpid. One option would be that the father will inform the child by sending it a SIGTERM on exit. But this will only work if the father won't get killed using SIGKILL. I would suggest to periodically send a signal using kill with param 0 to the father process. If this fails, the process has terminated.

From the kill(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.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
1

If the child exits, the parent will be sent a SIGCHLD. If the parent is going to die, it should notify the child somehow, or at least send it a SIGTERM.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

http://linux.die.net/man/2/waitpid

Wait for any child process, then exit when you return from waitpid.

KrisSodroski
  • 2,796
  • 3
  • 24
  • 39
-1

If the parent process exits, then the child process becomes a zombie process.

If the child exits, the parent can be notified by the wait system call. You can exit the parent by reading the status of it.

bazzinga
  • 219
  • 1
  • 8
  • If the parent exits, the child is inherited by `init` that is pid 1 by defintion. A child becomes a zombie if its own dead is not handled by (current) the parent. – alk Sep 07 '13 at 17:14