fileevent和在同一事件循环之后

时间:2014-10-20 12:22:53

标签: tcl

要解析日志文件,我想做类似这样的事情

  • 拖尾文件
  • 一段时间后编写解析数据并做其他事情

这是我的(示例)脚本

#!/usr/bin/tclsh

proc readfile {fd} {
    while {[gets $fd line] >= 0} {
        puts $line
    }
}

proc writefile {} {
    puts xxx
    flush stdout
}

if {$::argc > 0} {
    set fd [open [list | tail --follow=name --retry [lindex $argv 0] 2>@1]]
} else {
    set fd stdin
}

after 3000 writefile

fileevent $fd readable [list readfile $fd]

vwait done
close $fd

Tailing工作正常,但after的脚本没有被触发。

知道我做错了吗?

1 个答案:

答案 0 :(得分:1)

readfile proc中,您使用while导致其卡在其中,这就是after未被触发的原因。

#!/usr/bin/tclsh

proc readfile {fd} {
   global done
   puts "READ FILE CALLED..."
   gets $fd line; # Removed 'while' loop here
   puts "->>>>$line<<<<<<<<<"

   ### Your condition to exit the event handler#### 
   ### set done 1; #### Changing 'done' value to 1 after that condition ####
   ### So that the event handler will exit ####3
}

proc writefile {} {
    puts "WRITE FILE CALLED"
    puts xxx
    flush stdout
}

if {$::argc > 0} {
    set fd [open [list | tail --follow=name --retry [lindex $argv 0] 2>@1]]
} else {
    set fd stdin
}

after 3000 writefile

fileevent $fd readable [list readfile $fd]

vwait done
close $fd

输出

dinesh@dinesh-VirtualBox:~/pgms/tcl$ ./ubi.tcl 
WRITE FILE CALLED
xxx
ubi
READ FILE CALLED...
->>>>ubi<<<<<<<<<
cool
READ FILE CALLED...
->>>>cool<<<<<<<<<
working 
READ FILE CALLED...
->>>>working <<<<<<<<<