0. 概述

在执行命令行的时候,我一直有一个很不爽的事情就是有时一些命令因为网络等错误一直不返回,就 hang 在那,最严重的一次应该是刚开始玩 Go 没多久,对 dep 还不太熟的时候,挂了一晚上的 dep ensure 还没完,所以,我一直在寻找简单给命令行设置超时时间的方法,最后我发现了一条命令:timeout

1. 快速使用

通过 timeout,可以非常方便地设置命令行的运行时间,例如快速来个例子:

  1. [[email protected].io]# timeout 5s ping google.com
  2. PING google.com (172.217.175.78) 56(84) bytes of data.
  3. 64 bytes from nrt20s20-in-f14.1e100.net (172.217.175.78): icmp_seq=2 ttl=48 time=72.9 ms

就这么简单,当 ping www.google.com 执行了 5s 之后,不关是否成功都会直接退出了。

2. 更多参数

最简单的使用方式就是:timeout <duration> command,如果想玩得更深入一下,我们可以来看一下 timeout 命令的更多选项:

  1. [[email protected].io]# timeout --help
  2. Usage: timeout [OPTION] DURATION COMMAND [ARG]...
  3. or: timeout [OPTION]
  4. Start COMMAND, and kill it if still running after DURATION.
  5. Mandatory arguments to long options are mandatory for short options too.
  6. --preserve-status
  7. exit with the same status as COMMAND, even when the
  8. command times out
  9. --foreground
  10. when not running timeout directly from a shell prompt,
  11. allow COMMAND to read from the TTY and get TTY signals;
  12. in this mode, children of COMMAND will not be timed out
  13. -k, --kill-after=DURATION
  14. also send a KILL signal if COMMAND is still running
  15. this long after the initial signal was sent
  16. -s, --signal=SIGNAL
  17. specify the signal to be sent on timeout;
  18. SIGNAL may be a name like 'HUP' or a number;
  19. see 'kill -l' for a list of signals
  20. ... ...

3. Ref