为了账号安全,请及时绑定邮箱和手机立即绑定

如何在Bash中的给定超时后终止子进程?

如何在Bash中的给定超时后终止子进程?

FFIVE 2019-07-25 18:14:03
如何在Bash中的给定超时后终止子进程?我有一个bash脚本,它启动一个子进程,它不时地崩溃(实际上,挂起),而且没有明显的原因(关闭源,所以我无法对它做太多的事情)。因此,我希望能够在给定的时间内启动这个过程,如果它在给定的时间之后没有成功地返回,就会终止它。有没有简约和鲁棒性用bash实现这个目标的方法?告诉我这个问题是否更适合服务器故障或超级用户。
查看完整描述

3 回答

?
慕森卡

TA贡献1806条经验 获得超8个赞

# Spawn a child process:

(dosmth) & pid=$!

# in the background, sleep for 10 secs then kill that process

(sleep 10 && kill -9 $pid) &

或者也可以得到出口代码:


# Spawn a child process:

(dosmth) & pid=$!

# in the background, sleep for 10 secs then kill that process

(sleep 10 && kill -9 $pid) & waiter=$!

# wait on our worker process and return the exitcode

exitcode=$(wait $pid && echo $?)

# kill the waiter subshell, if it still runs

kill -9 $waiter 2>/dev/null

# 0 if we killed the waiter, cause that means the process finished before the waiter

finished_gracefully=$?



查看完整回答
反对 回复 2019-07-26
?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

我还问了这个问题,发现还有两件非常有用的事情:

  1. 秒变量(Bash)。
  2. 命令“pgrep”。

因此,我在命令行(OSX10.9)上使用了类似的内容:

ping www.goooooogle.com & PING_PID=$(pgrep 'ping'); SECONDS=0; while pgrep -q 'ping'; do sleep 0.2; 
if [ $SECONDS = 10 ]; then kill $PING_PID; fi; done

由于这是一个循环,我包括了一个“睡眠0.2”,以保持CPU凉爽。;-)

(顺便说一句:ping是个糟糕的例子,您只需要使用内置的“-t”(Timeout)选项。)




查看完整回答
反对 回复 2019-07-26
  • 3 回答
  • 0 关注
  • 614 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信