Process groups, sessions, parents and so on

From WTFwiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Here's a little program that can be used to help understand some of the intricate aspects:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void) {
        pid_t p;

        printf("parent: %d\n", getpid());
        if ((p = fork()) == 0) {
                if ((p = fork()) == 0) {
                        setsid();
                        if ((p = fork()) == 0) {
                                if ((p = fork()) == 0) {
                                        pause();
                                }
                                pause();
                        }
                        exit(0);
                }
                pause();
        }
        pause();

        return 0;
}

Compile and run this, and then check the results. On Linux, like this:

stian@ubuntu04:~$ ps -C poop -o pid,ppid,pgid,sid,tty,cmd
  PID  PPID  PGID   SID TT       CMD
17017  3516 17017  3516 pts/1    ./poop
17018 17017 17017  3516 pts/1    ./poop
17019 17018 17019 17019 ?        [poop] <defunct>
17020     1 17019 17019 ?        ./poop
17021 17020 17019 17019 ?        ./poop

Now let that sink in. Questions to ask yourself:

  1. Why is 17020's ppid 1?
  2. Why is session and process group different to begin with, then not?
  3. Why is one process defunct?
  4. Why don't the last 3 have a controlling tty?
  5. How come the first process got a new process group?
  6. Why is UNIX so complicated?

Note: The author (Stian) doesn't know the answers to several of these.