获取后台进程的退出代码 [英] Get exit code of a background process

查看:251
本文介绍了获取后台进程的退出代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从我的主要bourne shell脚本调用的命令CMD,该命令将永远持续下去.

I have a command CMD called from my main bourne shell script that takes forever.

我想按如下方式修改脚本:

I want to modify the script as follows:

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

有人可以给我指点一下吗?

Can someone give me pointers to accomplish this?

推荐答案

1:在bash中,$!保存上一次执行的后台进程的PID.无论如何,这将告诉您要监视什么过程.

1: In bash, $! holds the PID of the last background process that was executed. That will tell you what process to monitor, anyway.

4:wait <n>等待直到具有PID <n>的进程完成(它将阻塞直到该进程完成,因此您可能不希望在确定完成该过程之前调用它),然后返回完成过程的退出代码.

4: wait <n> waits until the process with PID <n> is complete (it will block until the process completes, so you might not want to call this until you are sure the process is done), and then returns the exit code of the completed process.

2、3:psps | grep " $! "可以告诉您该进程是否仍在运行.取决于您如何理解输出并决定输出与完成之间的距离. (ps | grep并非傻瓜式的.如果有时间,您可以想出一种更强大的方法来判断该进程是否仍在运行).

2, 3: ps or ps | grep " $! " can tell you whether the process is still running. It is up to you how to understand the output and decide how close it is to finishing. (ps | grep isn't idiot-proof. If you have time you can come up with a more robust way to tell whether the process is still running).

这是一个基本脚本:

# 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

这篇关于获取后台进程的退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆