Version 9 of fork

Updated 2009-06-20 13:25:37 by dkf

Fork is one of the primitives used for process creation in Unixy systems. It creates a copy of the process that calls it, and the only difference in internal state between the original and the copy is in the return value from the fork call (0 in the copy, but the pid of the copy in the parent).

Expect includes a fork. So does TclX.

Example:

    for {set i 0} {$i < 100} {incr i} {
        set pid [fork]
        switch $pid {
            -1 {
                puts "Fork attempt #$i failed."
            }
            0 {
                puts "I am child process #$i."
                exit
            }
            default {
                puts "The parent just spawned child process #$i."
            }
        }
    }

An other example script using fork is a unix style daemon.

In most cases though, one is not interested in spawning a copy of the process one already has, but rather wants a different process. When using POSIX APIs, this has to be done by first forking and then having the child use the exec system call to replace itself with a different program. The Tcl exec command does this fork&exec combination — in part because non-Unix OSs typicallly don't have "make a copy of parent process" as an intermediate step when spawning new processes.


stevel offers a version in Critcl

    package provide fork 1.0
    package require critcl

    critcl::cproc fork {} int {
        return fork();
    }

MG wonders if those package statements should be the other way around, so it only reports the package being available if critcl is too?

RS: True - I've even learnt somewhere that it's best to put the package provide at the very end of the code, so if any error occurs during development, the package isn't provided (and can be tried to reload, after fixing).


Fork will apparently not work unless threads are disabled when building TCL. See this thread on comp.lang.tcl: http://groups.google.com/group/comp.lang.tcl/browse_thread/thread/e62ae9431acbbeee

[Also add links to more technical discussions held on tcl-core mailing list.]