Using worker processes in Tcl
Written by Wojciech Kocjan   
Tcl pipes can be used to communicate with child processes - such as for long lasting calculations. Here's a quick example how to do this.

Running worker process is a common task and some misunderstanding might happen on how this could be done. The main idea is that parent opens a pipe to child process using open, child reads stdin and writes back to stdout. While the code itself is quite clumsy, it shows the basic concept.

Below is sample code for parent process:

Parent process
# read single line result
proc getdata {} {
    global pipe
    set eof 1
    catch {set eof [eof $pipe]}
    if {$eof} {
        puts stderr "Child terminated. Exiting."
        exit 0
    }
    set d [gets $pipe line]
    if {$d < 0} {return}
    puts "Result: $line"
}

# send single line command
proc senddata {line} {
    global pipe
    puts $pipe $line
    flush $pipe
}

# periodically send things to get calculated
proc timerdata {} {
    set a [expr {int(rand() * 1000)}]
    set b [expr {int(rand() * 1000)}]
    puts "Sending $a and $b"
    senddata [list $a $b]
    after 500 timerdata
}

# run child process and set up events for reading results
set pipe [open "|[list [info nameofexe] ./child.tcl]" r+]
fconfigure $pipe -translation lf -buffering line -blocking 0
fileevent $pipe readable getdata

after 500 timerdata
vwait forever
Below is sample code for child process:

Child process
# read line, calculate result and send it back
proc getdata {} {
    set eof 1
    catch {set eof [eof stdin]}
    if {$eof} {
        exit 0
    }
    set d [gets stdin line]
    if {$d < 0} {
        return
    }
    set a [lindex $line 0]
    set b [lindex $line 1]
    set c [expr {$a*$b}]
    puts $c
    flush stdout
}

fconfigure stdin -translation lf -buffering line -blocking 0
fconfigure stdout -translation lf -buffering line -blocking 0
fileevent stdin readable getdata

vwait forever

I'll try to rework this text later today.