【问题标题】:Running shell commands in background, in a tcl proc在后台运行 shell 命令,在 tcl proc 中
【发布时间】:2012-12-16 17:29:07
【问题描述】:

我正在尝试创建一个 tcl proc,它传递一个 shell 命令作为参数,然后打开一个临时文件并将格式化的字符串写入临时文件,然后在后台运行 shell 命令并将输出存储到临时文件也是如此。

在后台运行命令,以便之后可以立即调用 proc 将另一个参数传递给它,写入另一个文件。因此,运行一百个这样的命令所花费的时间不应该像串行运行它们那样长。多个临时文件最终可以连接成一个文件。

这是我正在尝试做的伪代码。

proc runthis { args }  
{ 
    set date_str [ exec date {+%Y%m%d-%H%M%S} ]
    set tempFile ${date_str}.txt
    set output [ open $tempFile a+ ]
    set command [concat exec $args]
    puts $output "### Running $args ... ###"   

    << Run the command in background and store output to tempFile >>
}

但是如何确保任务的后台处理正确完成?需要做些什么来确保正确关闭多个临时文件?

欢迎任何帮助。我是 tcl 的新手,我想解决这个问题。我读到过在 tcl 中使用线程,但我正在使用不支持线程的旧版本 tcl。

【问题讨论】:

  • 首先,过程主体的左大括号必须与proc 本身在同一逻辑行上(嗯,在其间可以有引用换行符,例如在参数列表中或反斜杠中,但这是大多数人不关心的改进)。
  • 其次,你可以使用clock formatclock seconds来做exec date的工作。请注意,为了将不同运行的输出分开,您还需要一个序列号(当然,如果两个运行在同一秒内开始)。
  • 考虑使用较少蹩脚的方法来创建临时文件。 This wiki page 有一个很好的选项摘要(file tempname 自 8.6 或 mkstemp(3)-仿真代码;作为个人经验,我发现 Stu 的版本对于旧 Tcls 来说还可以)。

标签: background tcl proc


【解决方案1】:

怎么样:

proc runthis { args }  { 
    set date_str [clock format [clock seconds] -format {+%Y%m%d-%H%M%S}]
    set tempFile ${date_str}.txt
    set output [ open $tempFile a+ ]
    puts $output "### Running $args ... ###"   
    close $output

    exec {*}$args >> $tempFile &
}

http://tcl.tk/man/tcl8.5/TclCmd/exec.htm

由于您似乎有一个旧的 Tcl,请替换

    exec {*}$args >> $tempFile &

    eval exec [linsert $args 0 exec] >> $tempFile &

【讨论】:

  • 您还需要一种方法来检测管道何时完成。幸运的是,后台 exec 的结果是生成的子进程的进程 ID 列表……
  • 当我使用以下命令时出现此错误“右大括号后的额外字符”:exec {*}$args >> $tempFile &
  • 在这种情况下,管道完成后我们需要做什么?我们需要关闭/冲洗一些东西吗?此外,如果 exec 返回进程 ID,我该如何检索它?
  • set pid [exec ...] - 简单的命令替换。如果您的程序/脚本在子流程完成后不需要执行任何操作,那么您就可以了。如果您收到错误“右大括号后的额外字符”,那么您可能使用的是旧 Tcl 版本 ({*} 字扩展
  • 这一行:eval exec [linsert $args exec] >> $tempFile & 给我这个错误:-wrong # args: should be "linsert list index element ?element ...?"跨度>
猜你喜欢
  • 2013-10-27
  • 1970-01-01
  • 2018-04-29
  • 2018-11-09
  • 1970-01-01
  • 2014-04-09
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
相关资源
最近更新 更多