这就是我需要发生的事情:
- 在后台启动进程A
- 等待 x 秒
- 在前台启动进程B
我怎样才能让等待发生?
我发现“睡眠”似乎停止了一切,而我实际上并不想“等待”进程 A 完全完成。我见过一些基于时间的循环,但我想知道是否有更干净的东西。
答案1
除非我误解了你的问题,否则它可以简单地通过这个简短的脚本来实现:
#!/bin/bash
process_a &
sleep x
process_b
(wait
如果您希望脚本在退出之前等待process_a
完成,请在末尾添加一个额外的内容)。
您甚至可以将其作为单行代码执行,无需脚本(如 @BaardKopperud 建议):
process_a & sleep x ; process_b
答案2
您可以使用后台控制运算符 (&)在后台运行一个进程sleep
命令在运行第二个进程之前等待,即:
#!/usr/bin/env bash
# script.sh
command1 &
sleep x
command2
以下是打印一些带有时间戳的消息的两个命令的示例:
#!/usr/bin/env bash
# Execute a process in the background
echo "$(date) - Running first process in the background..."
for i in {1..1000}; do
echo "$(date) - I am running in the background";
sleep 1;
done &> background-process-output.txt &
# Wait for 5 seconds
echo "$(date) - Sleeping..."
sleep 5
# Execute a second process in the foreground
echo "$(date) - Running second process in the foreground..."
for i in {1..1000}; do
echo "$(date) - I am running in the foreground";
sleep 1;
done
运行它以验证它是否表现出所需的行为:
user@host:~$ bash script.sh
Fri Dec 1 13:41:10 CST 2017 - Running first process in the background...
Fri Dec 1 13:41:10 CST 2017 - Sleeping...
Fri Dec 1 13:41:15 CST 2017 - Running second process in the foreground...
Fri Dec 1 13:41:15 CST 2017 - I am running in the foreground
Fri Dec 1 13:41:16 CST 2017 - I am running in the foreground
Fri Dec 1 13:41:17 CST 2017 - I am running in the foreground
Fri Dec 1 13:41:18 CST 2017 - I am running in the foreground
Fri Dec 1 13:41:19 CST 2017 - I am running in the foreground
Fri Dec 1 13:41:20 CST 2017 - I am running in the foreground
...
...
...
答案3
我喜欢@dr01的答案,但他没有检查退出代码,所以你不知道你是否成功。
这是一个检查退出代码的解决方案。
#!/bin/bash
# run processes
process_a &
PID1=$!
sleep x
process_b &
PID2=$!
exitcode=0
# check the exitcode for process A
wait $PID1
if (($? != 0)); then
echo "ERROR: process_a exited with non-zero exitcode" >&2
exitcode=$((exitcode+1))
fi
# check the exitcode for process B
wait $PID2
if (($? != 0)); then
echo "ERROR: process_b exited with non-zero exitcode" >&2
exitcode=$((exitcode+1))
fi
exit ${exitcode}
通常我将 PID 存储在 bash 数组中,然后 pid 检查是一个 for 循环。