在Mac OSx上有没有超时命令的替代方法?基本要求是我能够在指定的时间内运行命令。
例如:
timeout 10 ping google.com这个程序在Linux上运行了10秒的ping。
发布于 2014-01-15 00:06:14
您可以使用
brew install coreutils然后,当您需要超时时,使用
gtimeout..instead。为了解释为什么这里有一段来自Homebrew Caveats部分的片段:
注意事项
所有命令都已安装,前缀为“g”。
如果您确实需要将这些命令与其常规名称一起使用,则可以从bashrc将"gnubin“目录添加到您的路径中,如下所示:
PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH“
此外,如果您还从bashrc将"gnuman“目录添加到MANPATH,则可以使用普通名称访问他们的手册页:
MANPATH="/usr/local/opt/coreutils/libexec/gnuman:$MANPATH"
发布于 2016-02-20 02:27:44
另一种几乎可以跨平台工作的简单方法(因为它使用几乎无处不在的perl )是:
function timeout() { perl -e 'alarm shift; exec @ARGV' "$@"; }从这里被困住:https://gist.github.com/jaytaylor/6527607
而不是将其放入函数中,您只需将以下行放入脚本中,它也会起作用:
timeout.sh
perl -e 'alarm shift; exec @ARGV' "$@";或具有内置帮助/示例的版本:
timeout.sh
#!/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' "$@";发布于 2014-08-01 08:22:39
您可以使用以下命令限制任何程序的执行时间:
ping -t 10 google.com & sleep 5; kill $!https://stackoverflow.com/questions/3504945
复制相似问题