How exactly is 'fork' working in the reference example?


   (unless (fork) (do 5 (println 'OK) (wait 1000)) (bye))

The PicoLisp 'fork' maps to the underlying 'fork()' system call. When 'fork()' is called, a new process is created, and both processes (the parent and the child) continue to execute from that point. At that moment, both processes are identical, the only difference is that in the parent process fork() returns the child's process ID, while in the child 0 is returned.

The PicoLisp 'fork' function returns a number (the child's PID) in the parent process, and NIL in the child process. So in the above example

   (unless (fork)

is executed in the current process (which will be the "parent" thereafter), and (fork) returns the PID of the child. This is non-NIL, so the body of the 'unless' call is skipped by the parent, and it will continue execution with the next expression (not shown here).

In the child process, 'fork' returns NIL, and the body of the 'unless' call is executed. It consists of the two expressions

   (do 5 (println 'OK) (wait 1000))
   (bye)

This is the code the child process sees. It prints five times 'OK' and then exits (terminating the child process).

Note that the 'bye' is important, because otherwise the child would continue with the next (not shown) expression which was already executed by the parent 5 seconds before.

Thus,

   (unless (fork)
      (do-something)
      (bye) )

is a typical pattern to have (do-something) done in a child process. 'unless' begins execution only in the parent, but after its condition (the 'fork') is evaluated, we suddenly have two processes which execute different branches in the code (the next statement in the parent, and the body of 'unless' in the child). That's the reason for the name of that system call, "fork".

https://picolisp.com/wiki/?fork

19mar16    erik
Revision History