Sunday, April 25, 2010

Working with named pipes in tcl

Today I wanted to pipe lines of output from a C program into a TCL program using a named pipe, so that I didn't have to start them up at the same time. First I created the pipe with mkfifo:

$ mkfifo foo

Then here's the magic incantation in TCL to open the pipe and run a function every time something comes in:

set fifo [open "foo" {RDWR NONBLOCK}]
fconfigure $fifo -blocking 1
proc read_fifo {} {
global fifo

gets $fifo x
puts "x is $x"
}
fileevent $fifo readable read_fifo

Then when I write to the fifo, my program prints them:

$ echo "asdf" > foo

Make sure you write newlines when you write to the fifo so that gets doesn't block (or use read instead).

No comments: