我有一个从我的主 bourne shell 脚本中调用的命令 CMD,该命令需要很长时间。
我想修改脚本如下:
- 作为后台进程并行运行命令 CMD (
CMD &
).
- 在主脚本中,有一个循环每隔几秒监视生成的命令。该循环还向标准输出回显一些消息,指示脚本的进度。
- 当生成的命令终止时退出循环。
- 捕获并报告生成进程的退出代码。
有人可以指点我来完成这个任务吗?
1:在bash中,$!
保存最后执行的后台进程的PID。无论如何,这会告诉您要监视哪些进程。
4: wait <n>
等待直到有PID的进程<n>
完成(它将阻塞直到进程完成,因此在确定进程完成之前您可能不想调用此函数),然后返回已完成进程的退出代码。
2, 3: ps
or 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)