获取TCL中open创建的进程的返回码

Dan*_*ich 5 tcl

现在我正在通过 open 调用外部 bash 脚本,因为该脚本可能会运行几秒钟,也可能会运行几分钟。唯一可以确定的是:

  1. 它将输出必须向用户显示的文本。不是在脚本完成之后,而是在脚本仍在运行时。
  2. 会设置一个不同含义的返回码

读取并使用 shell 脚本输出的文本确实有效。但我不知道如何读取返回码。

(简化的)TCL 脚本如下所示:

#!/usr/bin/tclsh

proc run_script {} {
    set script "./testing.sh"

    set process [open "|${script}" "r"]
    chan configure $process -blocking 0 -translation {"lf" "lf"} -encoding "iso8859-1"

    while {[eof $process] == 0} {
        if {[gets $process zeile] != -1} {
            puts $zeile
        }

        update
    }
    close $process

    return "???"
}

set rc [run_script]
puts "RC = ${rc}"
Run Code Online (Sandbox Code Playgroud)

(简化的)shell 脚本看起来像这样:

#!/bin/bash

echo Here
sleep 1
echo be
sleep 2
echo dragons
sleep 4
echo ....
sleep 8

exit 20
Run Code Online (Sandbox Code Playgroud)

那么如何通过tcl读取shell脚本的返回码呢?

Sch*_*ron 4

您需要在关闭文件描述符之前将其切换回阻塞状态以获取退出代码。例如:

您可以使用try ... trap,它是在 tcl 8.6 中实现的:

chan configure $process -blocking 1
try {
    close $process
    # No error
    return 0
} trap CHILDSTATUS {result options} {
    return [lindex [dict get $options -errorcode] 2]
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用catch

chan configure $process -blocking 1
if {[catch {close $process} result options]} {
   if {[lindex [dict get $options -errorcode] 0] eq "CHILDSTATUS"} {
       return [lindex [dict get $options -errorcode] 2]
   } else {
       # Rethrow other errors
       return -options [dict incr options -level] $result
   }
}
return 0
Run Code Online (Sandbox Code Playgroud)