Linux 如何在 Bash 中运行超时的进程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10224939/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:52:23  来源:igfitidea点击:

How to run a process with a timeout in Bash?

linuxshelltimeout

提问by AlanF

Possible Duplicate:
Bash script that kills a child process after a given timeout

可能的重复:
在给定超时后杀死子进程的 Bash 脚本

Is there a way to write a shell script that would execute a certain command for 15 seconds, then kill the command?

有没有办法编写一个 shell 脚本来执行某个命令 15 秒,然后终止该命令?

I have tried sleep, wait and ping but maybe I am using them wrong.

我试过 sleep、wait 和 ping,但也许我用错了。

回答by ArjunShankar

Some machines don't have timeoutinstalled/available. In that case, you could background the process; its PID then gets stored as $!; then sleep for the required amount of time, then kill it:

有些机器没有timeout安装/可用。在这种情况下,你可以后台处理;它的PID然后被存储为$!; 然后睡眠所需的时间,然后杀死它:

some_command arg1 arg2 &
TASK_PID=$!
sleep 15
kill $TASK_PID

At this URLI find that there are mentioned, more than one solutions to make this happen.

这个 URL 上,我发现提到了不止一种解决方案来实现这一目标。

回答by Karoly Horvath

Use the timeoutcommand:

使用timeout命令:

timeout 15s command

Note: on some systems you need to install coreutils, on others it's missing or has different command line arguments. See an alternate solution posted by @ArjunShankar . Based on it you can encapsulate that boiler-plate code and create your own portable timeoutscript or small C app that does the same thing.

注意:在某些系统上您需要安装coreutils,在其他系统上它丢失或具有不同的命令行参数。请参阅@ArjunShankar 发布的替代解决方案。基于它,您可以封装样板代码并创建您自己的可移植timeout脚本或执行相同操作的小型 C 应用程序。