强制 wget 超时

tes*_*mus 7 linux wget ubuntu

如何强制 wget 在 X 秒后停止?

我有一个下载图像的脚本,有时它会卡住并拒绝“超时”。

我试过的:

--tries=3 --connect-timeout=30
Run Code Online (Sandbox Code Playgroud)

来自ps aux

root     26543  0.0  0.0  38636  1656 ?        S    20:40   0:00 wget -nc --tries=3 --connect-timeout=30 --restrict-file-names=nocontrol -O 18112012/image.jpg http://site/image.jpg
Run Code Online (Sandbox Code Playgroud)

Chr*_*odd 15

最简单的方法是使用timeout(1)命令,它是 GNU coreutils 的一部分,因此几乎可以在安装了 bash 的任何地方使用:

timeout 60 wget ..various wget args..
Run Code Online (Sandbox Code Playgroud)

或者如果您想在 wget 运行时间过长的情况下对其进行硬杀:

timeout -s KILL 60 wget ..various wget args..
Run Code Online (Sandbox Code Playgroud)

  • @kojiro:这个问题被标记为“ubuntu”,其中包括 GNU coreutils,如果你愿意的话,它可以很容易地安装在 Mac 上。 (2认同)

小智 2

您可以将 wget 命令作为后台进程运行,并在睡眠一定时间后发送 SIGKILL 将其强制杀死。

wget ... &
wget_pid=$!
counter=0
timeout=60
while [[ -n $(ps -e) | grep "$wget_pid") && "$counter" -lt "$timeout" ]]
do
    sleep 1
    counter=$(($counter+1))
done
if [[ -n $(ps -e) | grep "$wget_pid") ]]; then
    kill -s SIGKILL "$wget_pid"
fi
Run Code Online (Sandbox Code Playgroud)

解释:

  • wget ... &-&末尾的符号在后台运行命令,而不是在前台运行
  • wget_pid=$!-$!是一个特殊的 shell 变量,包含最近执行的命令的进程 ID。这里我们将其保存到一个名为 的变量中wget_pid
  • while [[ -n $(ps -e) | grep "$wget_pid") && "$counter" -lt "$timeout" ]]- 每隔一秒查找一次进程,如果还在,则继续等待,直到超时限制。
  • kill -s SIGKILL "$wget_pid"- 我们通过kill向后台运行的 wget 进程发送SIGKILL 信号来强制终止它。