Domanda

I have a question regarding named pipes in tcl.

First I created the pipe with mkfifo:

mkfifo foo 

Then execute the following tcl script:

set fifo [open "foo" r] 
fconfigure $fifo -blocking 1 
proc read_fifo {} { 
    global fifo 
    puts "calling read_fifo" 
    gets $fifo x 
    puts "x is $x" 
} 
puts "before file event" 
fileevent $fifo readable read_fifo 
puts "after file event" 

When i run the tcl script it waits for an event without outputting anything.

Then, when I write to the fifo:

echo "hello" > foo

Now, the tcl scripts prints out :

before file event 
after file event 

Why is 'read_fifo' function call not getting triggered here ?

Could anyone help me in understanding this behaviour.

È stato utile?

Soluzione

fileevent relies on the the eventloop, which you don't enter.
fileevent just tells Tcl to call read_fifo when it is readable.

If you want blocking IO, then just call gets. This blocks until an entire line has been read.

set fifo [open "foo" r] 
fconfigure $fifo -blocking 1 
gets $fifo x 
puts "x is $x"

If you do it event-driven, you need fileevent, use non-blocking IO and you have to enter the event-loop (e.g. with vwait forever).

set fifo [open "foo" r] 
fconfigure $fifo -blocking 0 
proc read_fifo {fifo} { 
    puts "calling read_fifo" 
    if {[gets $fifo x] < 0} {
        if {[eof $fifo]} {
           # Do some cleanup here.
           close $fifo
        }
    }
    puts "x is $x" 
} 
fileevent $fifo readable [list read_fifo $fifo]
vwait forever; #enter the eventloop

Don't mix event-driven with blocking IO. This does not really work.

Note that you don't have to call vwait in Tk, doing so would reenter the event-loop, which is considered bad practice.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top