如何 运行 两个命令,但在不停止第一个命令的情况下延迟第二个命令?

How to run two commands, but with a delay on the second command without stopping the first command?

我正在尝试执行以下操作(在 Raspberry Pi 3 上 Raspbian OS):

  1. 开始基准测试(sysbench
  2. 然后 运行 一些监控工具(iostatmpstat)经过一些延迟,比如 5 秒,作为预热间隔

所以我制作了以下基本脚本:

#!/bin/bash
for x in 16000 32000 64000 128000
do
  echo "max-prime = $x"
  (sysbench --test=cpu --cpu-max-prime=$x --num-threads=4 run >> results.out) & (sleep 5s && mpstat >> mpstat.out & iostat >> iostat.out)
done

我尝试了上面第 5 行的更多变体,但 sysbench 没有正确执行(我想是因为 sleep?)。 results.out里面写的输出只有这样,因为循环重复了4次:

sysbench 0.4.12: multi-threaded system evaluation benchmark

Running the test with following options:
Number of threads: 4

Doing CPU performance benchmark

Threads started!

如何在 5 秒后执行 sysbench 和 运行 监控工具,而不影响 sysbench

您可以将 ; 命令分隔符与 & 混合使用以将进程置于后台。

foo & sleep 5; bar &

在您的情况下,您想循环执行此操作。如果要等待 foo 完成后再继续下一次循环迭代,请使用 wait.

for  ... ; do
    foo & sleep 5; bar
    wait
done

在这里多加一对括号:

... & (sleep 5s && (mpstat >> mpstat.out & iostat >> iostat.out))
                   ^                                           ^

如果将命令放在不同的行中,您会更轻松。

for x in 16000 32000 64000 128000
do
  echo "num of threads = $x"
  sysbench --test=cpu --cpu-max-prime=$x --num-threads=4 run >> results.out &
  sleep 5s
  mpstat >> mpstat.out
  iostat >> iostat.out
done

您需要等到基准测试完成后再进入下一个循环。我建议将 waitkill %% 放在循环的末尾以等待或停止它。