我有一个从我的主 bourne shell 脚本调用的命令 CMD,它需要很长时间。
我想修改脚本如下:
CMD &
)。有人可以给我指点来完成这个吗?
最佳答案
1:在 bash 中,$!
保存最后执行的后台进程的 PID。无论如何,这会告诉你要监控什么进程。
4: wait <n>
等待PID为<n>
的进程完成(它会阻塞直到进程完成,所以你可能不想在确定进程完成之前调用它),然后返回已完成进程的退出代码。
2, 3: ps
或 ps | grep " $! "
可以告诉你进程是否还在运行。如何理解输出并决定距离完成有多近取决于您。 (ps | grep
并不是万无一失的。如果你有时间,你可以想出一个更可靠的方法来判断进程是否仍在运行)。
这是一个框架脚本:
# simulate a long process that will have an identifiable exit code
(sleep 15 ; /bin/false) &
my_pid=$!
while ps | grep " $my_pid " # might also need | grep -v grep here
do
echo $my_pid is still in the ps output. Must still be running.
sleep 3
done
echo Oh, it looks like the process is done.
wait $my_pid
# The variable $? always holds the exit code of the last command to finish.
# Here it holds the exit code of $my_pid, since wait exits with that code.
my_status=$?
echo The exit status of the process was $my_status
https://stackoverflow.com/questions/1570262/