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

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

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

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

3 回答

?
湖上湖

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

# 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
  • 3 回答
  • 0 关注
  • 369 浏览
慕课专栏
更多

添加回答

举报

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