Orphaned Processes

You may have noticed when running the examples in the last chapter that when child processes are involved, it’s no longer possible to control everything from a terminal like we’re used to.

When starting a process via a terminal, we normally have only one process writing to STDOUT, taking keyboard input, or listening for that Ctrl-C telling it to exit.

But once that process has forked child processes that all becomes a little more difficult. When you press Ctrl-C which process should exit? All of them? Only the parent?

It’s good to know about this stuff because it’s actually very easy to create orphaned processes:

fork do
  5.times do
    sleep 1
    puts "I'm an orphan!"
  end
end

abort "Parent process died..."

If you run this program from a terminal you’ll notice that since the parent process dies immediately the terminal returns you to the command prompt. At which point, it’s overwritten by the STDOUT from the child process! Strange things can start to happen when forking processes.

Abandoned Children

What happens to a child process when its parent dies?

The short answer is, nothing. That is to say, the operating system doesn’t treat child processes any differently than any other processes. So, when the parent process dies the child process continues on; the parent process does not take the child down with it.

Managing Orphans

Can you still manage orphaned processes?

We’re getting a bit ahead of ourselves with this question, but it touches on two interesting concepts.

The first is something called daemon processes. Daemon processes are long running processes that are intentionally orphaned and meant to stay running forever. These are covered in detail in a later chapter.

The second interesting bit here is communicating with processes that are not attached to a terminal session. You can do this using something called Unix signals. This is also covered in more detail in a later chapter.

We’ll soon talk about how to properly manage and control child processes.