击:用等待超时 [英] Bash: wait with timeout
问题描述
在一个Bash脚本,我愿做这样的事情:
In a Bash script, I would like to do something like:
app1 &
pidApp1=$!
app2 &
pidApp2=$1
timeout 60 wait $pidApp1 $pidApp2
kill -9 $pidApp1 $pidApp2
即,推出的背景下两个应用程序,并给他们60秒的时间完成自己的工作。然后,如果他们不说时间内完成,杀死他们。
I.e., launch two applications in the background, and give them 60 seconds to complete their work. Then, if they don't finish within that interval, kill them.
不幸的是,上述方法无效,因为暂停
是可执行文件,而等
是一个shell命令。我试图将其更改为:
Unfortunately, the above does not work, since timeout
is an executable, while wait
is a shell command. I tried changing it to:
timeout 60 bash -c wait $pidApp1 $pidApp2
但是,这仍然不起作用,因为等
只能在同一壳体内推出了PID。
But this still does not work, since wait
can only be called on a PID launched within the same shell.
任何想法?
推荐答案
写的PID文件和启动这样的应用程序:
Write the PIDs to files and start the apps like this:
pidFile=...
( app ; rm $pidFile ; ) &
pid=$!
echo $pid > $pidFile
( sleep 60 ; if [[ -e $pidFile ]]; then killChildrenOf $pid ; fi ; ) &
killerPid=$!
wait $pid
kill $killerPid
这将创建另一个进程休眠超时和终止进程,如果它至今尚未完成。
That would create another process that sleeps for the timeout and kills the process if it hasn't completed so far.
如果该过程完成得更快,PID文件被删除,并且凶手的过程被终止。
If the process completes faster, the PID file is deleted and the killer process is terminated.
killChildrenOf
是提取的所有进程,并杀死了一定PID的所有儿童的脚本。看到这个问题的答案了不同的方式来实现这个功能:最好的方法杀死所有子进程
killChildrenOf
is a script that fetches all processes and kills all children of a certain PID. See the answers of this question for different ways to implement this functionality: Best way to kill all child processes
如果您想一步BASH之外,你可以写PID和超时到一个目录,看该目录。每分钟左右,请阅读条目,并检查哪些过程仍然围绕他们是否超时。
If you want to step outside of BASH, you could write PIDs and timeouts into a directory and watch that directory. Every minute or so, read the entries and check which processes are still around and whether they have timed out.
修改如果你想知道这个过程是否成功地死了,你可以使用杀-0 $ PID
EDIT If you want to know whether the process has died successfully, you can use kill -0 $pid
这篇关于击:用等待超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!