Skip to content

Instantly share code, notes, and snippets.

@gsauthof
Created November 27, 2016 09:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsauthof/8c8406748e536887c45ec14b2e476cbc to your computer and use it in GitHub Desktop.
Save gsauthof/8c8406748e536887c45ec14b2e476cbc to your computer and use it in GitHub Desktop.
Illustrating how orphaned children aren't necessarily adopted 2 by PID 1
/* For illustrating how orphaned children aren't necessarily adopted
by PID 1.
See also: http://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits/36945270#36945270
2016, Georg Sauthoff <mail@georg.so>
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
int main()
{
fprintf(stderr, "grandparent: %ju (ppid %ju)\n",
(uintmax_t) getpid(), (uintmax_t)getppid());
int pid = fork();
if (pid == -1) { perror(0); exit(1); }
if (pid) { // parent
sleep(3);
fprintf(stderr, "granparent %ju exiting\n", (uintmax_t) getpid());
} else { // child
fprintf(stderr, "parent: %ju (ppid %ju)\n",
(uintmax_t) getpid(), (uintmax_t)getppid() );
int pid2 = fork();
if (pid2 == -1) { perror(0); exit(1); }
if (pid2) { //parent
fprintf(stderr, "parent %ju exiting\n", (uintmax_t) getpid());
} else { // child
sleep(1);
fprintf(stderr, "child: %ju (ppid %ju)\n",
(uintmax_t) getpid(), (uintmax_t) getppid());
fprintf(stderr, "child %ju exiting\n", (uintmax_t) getpid());
}
}
return 0;
}
/* Example output on Fedora 25, inside Wayland and a Gnome terminal:
$ pstree -ps $$
systemd(1)───systemd(1750)───gnome-terminal-(2250)───zsh(8375)─┬─pstree(9080)
└─vim(8431)
$ cc -Wall -g fork.c -o fork
$ ./fork
grandparent: 9102 (ppid 8375)
parent: 9103 (ppid 9102)
parent 9103 exiting
child: 9104 (ppid 1750)
child 9104 exiting
granparent 9102 exiting
Note that the ppid of the child is 1750 and not (as perhaps traditionally
expected) 1.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment