启动后台进程并检查它何时结束

启动后台进程并检查它何时结束

如何在后台启动进程并检查它何时在 bash 脚本中结束?我的想法是这样的脚本:

launch backgroundprocess &
while [ Process is running ];do
   echo "PROCESS IS RUNNING\r"
done;

echo "PROCESS TERMINATED"

答案1

关键是“等待”命令:

#!/bin/bash

/my/process &
/another/process &
wait
echo "All processes done!"

答案2

wait可以拥有所需的粒度:

sleep 1 &
PID1=$!
sleep 2 &
PID2=$!

wait $PID1
echo 'PID1 has ended.'
wait
echo 'All background processes have exited.'

答案3

这是一种方法:

launch backgroundprocess &
PROC_ID=$!

while kill -0 "$PROC_ID" >/dev/null 2>&1; do
    echo "PROCESS IS RUNNING"
done
echo "PROCESS TERMINATED"
exit 0

答案4

您可以使用 nohup 运行进程并编写 shell 脚本来读取 nohup 用于记录的 nohup.out 文件。

  nohup command &

相关内容