1

On a Unix system, there are two circumstances where getppid will return 1: either the calling process' original parent has exited, or it was directly started by init. Sometimes one might wish to behave differently depending on which of the two it is; for example, the program in this question wants to exit when its parent does, and one way to detect that is to notice that the value returned by getppid is now 1, but init never exits, so if the program was directly started by init it should not exit. You can't tell by calling getppid at the very beginning of main, because your parent might have exited before you ever get a chance to run — if it did the double-fork trick to dissociate from a shell, for instance.

In days of yore, being directly started by init was only a realistic possibility for a tiny handful of processes, /etc/rc and maybe some gettys, but nowadays we have containers and much more powerful "system manager" programs run as init, so it's much more likely to come up.

So the question is, is there any 100% reliable way for a program to tell whether its original parent was init? OS-specific answers are OK, I'm almost certain there's no way to do it within POSIX.

zwol
  • 135,547
  • 38
  • 252
  • 361

0 Answers0