Skip to content

Process Tree

You'll fork, exec and wait by hand, then make a zombie and an orphan on purpose so you know what each one looks like in ps.

About

Every program you've ever launched was started by fork and exec, and they're simpler than they sound. You'll write a program that splits itself in two, has the child become a different program, and has the parent wait for the exit code. Then you'll make a zombie and an orphan on purpose and watch them in ps, which is the fastest way to understand why they exist. One safety note: a fork inside a loop with no limit is a fork bomb and will freeze your machine, so run ulimit -u 200 in the shell before you experiment.

At a glance

Per requirement
15 XP
Completion bonus
75 XP
Requirements
5
Takes
One evening
Skill level
Beginner (done it a few times)
Cost
Free
Supplies
You need some
Where
At home
Other people
On your own

Requirements

  1. 1
    Fork once and have both processes print their own PID and their parent's PID. Call fork, check the return value for the child, the parent and an error, and use getpid and getppid in both branches. Run it three times and notice the order of the output isn't fixed. Take a screenshot of the output from all three runs. Photo
  2. 2
    Have the child exec ls and the parent wait for it and print the exit status. Use execvp in the child, and waitpid in the parent with WEXITSTATUS to pull out the code. Then run a command that fails, like ls on a folder that doesn't exist, and show the nonzero code. Take a screenshot of both runs. Photo
  3. 3
    Make a zombie on purpose and catch it in ps before cleaning it up. Have the child exit immediately and the parent sleep for 30 seconds without calling wait. In another terminal run ps aux and find the line marked Z or defunct. Then add the wait and show the zombie is gone. Take a screenshot of the ps line with the zombie. Photo
  4. 4
    Make an orphan by having the parent exit first, and show who adopted it. Have the parent exit right away while the child sleeps, then print the child's parent PID from inside it after a second. On most systems it's 1 or a user session process. Take a screenshot showing the new parent. Photo
  5. 5
    Draw the process tree for your shell running your program running ls. Use pstree, or ps -o pid,ppid,command, from your terminal down to ls. Then draw the same tree on paper with the four system calls (fork, exec, wait, exit) written next to the arrows where they happen. Take a photo of the drawing next to the ps output. Photo