【问题标题】:How to get the execution time of child and offspring process in shell script?如何在shell脚本中获取子进程和子进程的执行时间?
【发布时间】:2014-02-17 02:19:53
【问题描述】:

我想在后台运行test1.sh、test2.sh和test3.sh并分别记录执行时间。所以我使用了以下命令。

time `./test1.sh & ; wait` > record_1
time `./test2.sh & ; wait` > record_2
time `./test3.sh & ; wait` > record_3

虽然 test1.sh 中的内容可能会调用其他脚本:

./other_test1.sh &

所以 test2.sh 和 test3.sh 可以调用 ./other_test2.sh & 和 ./other_test3.sh &

之所以要使用wait是因为test1.sh等会fork子进程,我希望执行时间包括子进程和子进程的执行时间。但是它导致了如下错误:

bash: command substitution: line 1: syntax error near unexpected token `;'
bash: command substitution: line 1: `./test2 & ;wait'

我的想法是在 backsticks 部分,wait 命令将等待像 test1.sh 这样的后台脚本被终止。我无法弄清楚语法出了什么问题。

【问题讨论】:

  • 你的previous question 是一样的,你得到了答案。你不是吗?
  • 我认为上一个问题和这个问题有点不同。在上一个中,我想知道launcher.sh 的总执行时间。所以使用wait等待test1.sh、test2.sh和test3.sh就可以了。但是在这个问题中,我想记录启动器将调用的 test.sh 的每次执行时间。在我问了上一个问题之后,我认为如果我可以通过获取每个执行时间来获得更多的执行时间细节会更好。

标签: linux bash shell process fork


【解决方案1】:

由于&; 都是分隔命令且具有相同优先级的列表运算符,因此不能同时使用它们。这样做类似于同时使用多个条件列表运算符,如command1 && || command2。这是一个逻辑矛盾。

要绕过这个可以理解的限制,您可以使用子 shell (...)\ 来继续这一行。

time (./test1.sh & \ wait) &> record_1
time (./test2.sh & \ wait) &> record_2
time (./test3.sh & \ wait) &> record_3

【讨论】:

    【解决方案2】:

    如果要测量 test.sh 的执行时间,则不需要&; wait。此外,您不能仅使用> 重定向时间输出。用这个: bash -c 'time ./test1.sh' &> record_1

    所以你可能会得出以下结论:

    bash -c 'time ./test1.sh' &> record_1
    bash -c 'time ./test2.sh' &> record_2
    bash -c 'time ./test3.sh' &> record_3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-21
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 2012-03-04
      • 1970-01-01
      • 2014-04-19
      相关资源
      最近更新 更多