Tcl question: fileevent: Does it block?

Joel Hammer joel
Mon May 17 11:57:41 PDT 2004


Well, I know everybody has been worrying about this problem, so here is
a solution.

#!/etc/alternatives/wish -f
proc ReadPipe {} {
global id
if {$id == "undefined"} {
    set  id [ open /tmp/NewPipe {RDONLY NONBLOCK} ]
    fileevent $id readable [list ReadPipe]
                         }
    while {![eof $id]} {
        gets $id f
        puts $f
        }
close $id
set  id [ open /tmp/NewPipe {RDONLY NONBLOCK} ]
fileevent $id readable [list ReadPipe]
}
# ====This is the start of the script
set id "undefined"
ReadPipe

The brilliant insight is that the pipe seems to close itself for reading
after a read, so, the procedure has to read the pipe, close the pipe,
and then reopen it and reset the file event. I haven't come across this
method in any of the demos or the welch book, so this may be all wrong,
but, it works here.

This looks like a great thing, file events. You could have one master tcl
script running which is watching lots of named pipes, and does whatever
based on what comes in the pipes from numerous other programs. I am
feeling a surge of power.

One odd thing about reading from these named pipe. If you have a counter
in the gets loop, like:
incr i
puts $i
there are two blank lines generated with each get with:
  echo text > Pipe
If you use:
  echo text > Pipe &
You get about 120 blank lines. 
This behavior is not noticeable when you leave out the counter.

Joel




More information about the Linux-users mailing list