How does fork's behavior differ in child process

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2022-05-26

After fork(), both the parent and the child processes execute the subsequent code in parallel.

But you can also make their execution paths differ if desired.

If the fork() call succeeds, the PID of the child process is returned in the parent, whereas 0 is returned in the child.

Thus you can do this:

if fork
  puts "Parent only #{}"
  puts "Child only #{}"

Note, however, that this does not work when using blocks.

child_pid = fork { puts "Child only #{}" }

# Problematic code
if child_pid !=0
  puts "Parent only #{}"
  raise ThisWillActuallyNeverBeRun

(Essentially this last example shows how blocks are alternative flow control mechanisms)