# 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:
# 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