TCL:我们是否可以使用exec在后台运行程序,同时适当地捕获错误代码? [英] TCL: Can we use exec to run a program in background, and yet capture the error codes appropriately?

查看:53
本文介绍了TCL:我们是否可以使用exec在后台运行程序,同时适当地捕获错误代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Tcl时,我尝试使用Tcl中的";try";命令作为后台进程,并返回错误代码。但是,使用与号(&;)始终返回错误代码0,表示运行成功。

try {
        exec cmd /c test.exe &
        set returnvalue 0
    } on ok {output} {
        puts "Command successful"
    } trap {CHILDSTATUS} {output options} {
        set result [lindex [dict get $options -errorcode] end]
        if {$result == 3} {
            puts "Argument undefined"
        } elseif {$result == 4} {
            puts "Login Failed"
        } elseif {$result == 1} {
            puts "Process Cancelled by user"
        }
    }
如何指示解释器在后台执行test.exe并返回相应的错误代码? 我的目的是并行运行test.exe和另一个程序,同时根据错误代码从test.exe运行和后处理中读取错误代码。

有什么专家建议吗?

推荐答案

若要在后台运行进程获取其退出代码,您必须切换到使用open "|cmd /c ... &"和fileEvents。然后捕获close命令(在阻塞模式下)以获得最终结果:

# Helper proc to run commands in the background
proc bgexec {args} {
    set fd [open "|$args &"]
    fconfigure $fd -blocking 0
    fileevent $fd readable [list bgevent $fd [join $args]]
}

# Helper proc to handle file events
proc bgevent {fd cmd} {
    # Discard any output
    read $fd
    if {[eof $fd]} {
        fconfigure $fd -blocking 1
        try {
            close $fd
        } on ok {output} {
            puts "$cmd: Command successful"
        } trap {CHILDSTATUS} {output options} {
            set result [lindex [dict get $options -errorcode] end]
            if {$result == 3} {
                puts "$cmd: Argument undefined"
            } elseif {$result == 4} {
                puts "$cmd: Login Failed"
            } elseif {$result == 1} {
                puts "$cmd: Process Cancelled by user"
            }
        }
    }
}

bgexec cmd /c test.exe 
bgexec cmd /c test.exe arg1

vwait forever

这篇关于TCL:我们是否可以使用exec在后台运行程序,同时适当地捕获错误代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆