从tclsh调用bash内置函数

时间:2012-01-04 13:42:45

标签: bash tcl built-in

我有一个tclsh脚本,我需要在后台执行某些命令。 我可以使用exec命令从tcl实现这一点:exec myprog &

但我怎么能等待myprog从tcl完成。 命令wait不是独立的实用程序,因此我可以将其与exec一起使用。 wait命令是内置的shell。请让我知道如何在tclsh脚本中等待后台进程。

PS:我在剧本中使用#!/ usr / bin / env tclsh shebang。

1 个答案:

答案 0 :(得分:3)

如果你想在Tcl的后台执行一个命令,你可以去寻找以下内容:

proc cb { fd } {
        gets $fd buf
        append ::output $buf
        if {[eof $fd]} {
            close $fd
            set ::finished 1
        }
}

set command "<command to execute>"
set ::output ""
set ::finished 0
set fd [open "|$command" r]
fconfigure $fd -blocking no
fileevent $fd readable "cb $fd"
vwait ::finished
puts $::output

在命令之前使用open|将允许您“打开”命令的管道。使用fconfigure将其设置为非阻塞将允许您从中读取而不会锁定脚本中的任何其他进程。只要有要读取的数据(fileevent标志),cb就会调用指定的回调proc(在本例中为readable)。 vwait将确保脚本在写入指定变量之前不会继续执行,因此$command将在后台执行,允许说Tk接口保持响应并等待直到您想要继续