bash 如何检查后台作业是否还活着?(重击)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11239466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check whether a background job is alive? (bash)
提问by X?pplI'-I0llwlg'I -
I have the following bash script, we can call it script1.sh
:
我有以下 bash 脚本,我们可以称之为script1.sh
:
#!/bin/bash
exec ./script2.sh &
sleep 5
if job1 is alive then #<--- this line is pseudo-code!
exec ./script3.sh &
wait
fi
As can be seen, the script executes script2.sh
as a background job and then waits 5 seconds (so script2.sh
can do some initialization stuff). If the initialization succeeds, the script2.sh
job will still be alive, in which case I also want to start script3.sh
concurrently; if not, I just want to quit.
可以看出,脚本script2.sh
作为后台作业执行,然后等待 5 秒(因此script2.sh
可以执行一些初始化操作)。如果初始化成功,script2.sh
job还是存活的,这种情况我也想script3.sh
并发启动;如果没有,我只想退出。
However, I do not know how to check whether the first job is alive, hence the line of pseudo-code. So, what should go in its place?
但是,我不知道如何检查第一个作业是否还活着,因此是伪代码行。那么,应该怎么做呢?
采纳答案by Todd A. Jacobs
You can get the PID of the most recent background job with $!
. You could then check the exit status of psto determine if that particular PID is still in the process list. For example:
您可以使用$!
. 然后您可以检查ps的退出状态以确定该特定 PID 是否仍在进程列表中。例如:
sleep 30 &
if ps -p $! >&-; then
wait $!
else
jobs
fi
回答by ormaaj
You can check if a signal is deliverable
您可以检查信号是否可交付
./script2 &
myPid=$!
sleep 5
if kill -0 "$myPid"; then
script3 &
wait
fi
回答by Gerald Combs
To expand on fduff's answer you can use the jobs
builtin:
要扩展 fduff 的答案,您可以使用jobs
内置命令:
if jobs %%; then
exec ./script3.sh &
wait
fi
jobs %%
prints the job ID of the most recent background process (the "current job") and returns 0 on success or 1 if there is no such job.
jobs %%
打印最近后台进程(“当前作业”)的作业 ID,成功时返回 0,如果没有这样的作业,则返回 1。
回答by bobah
I am not sure exec works with background, as it replaces the image of the parent process with that of the child process, otherwise, if we assume you get rid of exec, you'd want something like:
我不确定 exec 是否适用于后台,因为它将父进程的图像替换为子进程的图像,否则,如果我们假设您摆脱了 exec,您会想要类似的东西:
#!/bin/bash
./script2.sh&
pid1=$!
if kill -0 $pid1; then
./script3.sh&
pid3=$!
wait
fi
回答by Ivan
Copy your background process pid into a var
将您的后台进程 pid 复制到 var
./script2.sh &; pid=$!
And then check if this pid exist in /proc
dir
然后检查这个pid是否存在于/proc
dir中
[[ -e /proc/$pid ]] && { yor_code; }
Or with ls
或与 ls
ls /proc/$pid 2>/dev/null && { yor_code; }
回答by fduff
Have a look at the jobs
command; it lists all running jobs.
看看jobs
命令;它列出了所有正在运行的作业。