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 #{Process.pid}"
else
  puts "Child only #{Process.pid}"
end

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

child_pid = fork { puts "Child only #{Process.pid}" }

# Problematic code
if child_pid !=0
  puts "Parent only #{Process.pid}"
else
  raise ThisWillActuallyNeverBeRun
end

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