【发布时间】:2011-03-31 02:47:07
【问题描述】:
Mac OSx 上的超时命令是否有替代方法。基本要求是我能够在指定的时间内运行命令。
例如:
timeout 10 ping google.com
这个程序在 Linux 上运行 ping 10 秒。
【问题讨论】:
Mac OSx 上的超时命令是否有替代方法。基本要求是我能够在指定的时间内运行命令。
例如:
timeout 10 ping google.com
这个程序在 Linux 上运行 ping 10 秒。
【问题讨论】:
你可以使用
brew install coreutils
然后当你需要超时时,使用
gtimeout
..相反。为了解释为什么这里有一个来自 Homebrew Caveats 部分的 sn-p:
注意事项
所有命令都安装了前缀“g”。
如果你真的需要用它们的正常名称来使用这些命令,你 可以从 bashrc 中将“gnubin”目录添加到 PATH,例如:
PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"此外,如果您添加,您可以使用正常名称访问他们的手册页 也可以从 bashrc 将“gnuman”目录添加到 MANPATH:
MANPATH="/usr/local/opt/coreutils/libexec/gnuman:$MANPATH"
【讨论】:
ln -s /usr/local/bin/gtimeout /usr/local/bin/timeout 仅启用一个命令(别名解决方案适用于交互式 CLI 使用,但不适用于从 bash 脚本调用时)。
brew install coreutils 安装了coreutils,并且timeout 命令在没有前缀的情况下可用。
另一种几乎可以跨平台工作的简单方法(因为它使用几乎无处不在的 perl)是这样的:
function timeout() { perl -e 'alarm shift; exec @ARGV' "$@"; }
从这里抓取: https://gist.github.com/jaytaylor/6527607
您可以将以下行放入脚本中,而不是将其放入函数中,它也可以工作:
perl -e 'alarm shift; exec @ARGV' "$@";
或内置帮助/示例的版本:
#!/usr/bin/env bash
function show_help()
{
IT=$(cat <<EOF
Runs a command, and times out if it doesnt complete in time
Example usage:
# Will fail after 1 second, and shows non zero exit code result
$ timeout 1 "sleep 2" 2> /dev/null ; echo \$?
142
# Will succeed, and return exit code of 0.
$ timeout 1 sleep 0.5; echo \$?
0
$ timeout 1 bash -c 'echo "hi" && sleep 2 && echo "bye"' 2> /dev/null; echo \$?
hi
142
$ timeout 3 bash -c 'echo "hi" && sleep 2 && echo "bye"' 2> /dev/null; echo \$?
hi
bye
0
EOF
)
echo "$IT"
exit
}
if [ "$1" == "help" ]
then
show_help
fi
if [ -z "$1" ]
then
show_help
fi
#
# Mac OS-X does not come with the delightfully useful `timeout` program. Thankfully a rough BASH equivalent can be achieved with only 2 perl statements.
#
# Originally found on SO: http://stackoverflow.com/questions/601543/command-line-command-to-auto-kill-a-command-after-a-certain-amount-of-time
#
perl -e 'alarm shift; exec @ARGV' "$@";
【讨论】:
perl -e 'alarm shift; exec "ping google.com" 之类的东西?
Alarm clock 消息,并消除此gets messy。
function timeout() { perl -e 'use Time::HiRes "ualarm"; ualarm shift; exec @ARGV' "$@"; }(请注意,根据perldoc.perl.org/functions/alarm.html,它需要 Perl >= 5.8)
您可以使用此命令限制任何程序的执行时间:
ping -t 10 google.com & sleep 5; kill $!
【讨论】:
来自 Ubuntu / Debian 的 Timeout 包可以在 Mac 上编译并且可以工作。 该软件包可在http://packages.ubuntu.com/lucid/timeout获取。
【讨论】:
brew install coreutils - 然后使用 gtimeout 或将您的 PATH 设置为使用 timeout 名称。
timeout 包。 timeout 命令由coreutils 提供。
【讨论】:
你可以ping -t 10 google.com >nul
>nul 去掉了输出。因此,它不会显示 64 BYTES FROM 123.45.67.8 BLAH BLAH BLAH 它只会显示一个空白换行符,直到超时。 -t 标志可以更改为任意数字。
【讨论】:
>nul 是 Windows 的东西。在 macOS 上,这实际上会创建一个名为 nul 的文件并将输出重定向到它