linux - 获取后台进程的退出代码

我有一个从我的主 bourne shell 脚本调用的命令 CMD,它需要很长时间。

我想修改脚本如下:

  1. 将命令 CMD 作为后台进程并行运行 (CMD &)。
  2. 在主脚本中,每隔几秒就有一个循环来监控生成的命令。该循环还会将一些消息回显到标准输出,指示脚本的进度。
  3. 当生成的命令终止时退出循环。
  4. 捕获并报告衍生进程的退出代码。

有人可以给我指点来完成这个吗?

最佳答案

1:在 bash 中,$!保存最后执行的后台进程的 PID。无论如何,这会告诉你要监控什么进程。

4: wait <n>等待PID为<n>的进程完成(它会阻塞直到进程完成,所以你可能不想在确定进程完成之前调用它),然后返回已完成进程的退出代码。

2, 3: psps | 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/

相关文章:

linux - Linux 的虚拟串行端口

linux - 如何获取终端的字符编码

python - 如何模拟请求和响应?

python - 在 Python 中循环列表

python - 在 Python 中使用 "continue"语句的示例?

python - 谁能解释python的相对进口?

python - Django 数据库设置 'Improperly Configured' 错误

python - 如何在 Python 中创建不可变对象(immutable对象)?

mysql - 重命名 MySQL 数据库

linux - bash中带有变量的别名