在 Linux 上,ping
行为不一致。如果它最初没有网络连接,它会终止并显示以下消息
user@machine:~$ ping 8.8.8.8
connect: Network is unreachable
user@machine:~$
但是,如果有连接但断开了,它会继续尝试 ping:
user@machine:~$ ping 8.8.8.8
64 bytes from 8.8.8.8: icmp_seq=1 ttl=120 time=37.4 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=120 time=37.4 ms
ping: sendmsg: Network is unreachable
ping: sendmsg: Network is unreachable
ping: sendmsg: Network is unreachable
64 bytes from 8.8.8.8: icmp_seq=6 ttl=120 time=37.8 ms
64 bytes from 8.8.8.8: icmp_seq=7 ttl=120 time=35.1 ms
* ... etc ... *
我经常用ping
它来监控我的互联网连接状态,尤其是在不稳定的 Wifi 上,如果最初没有连接,让 ping“继续尝试”会很棒。(我在 Mac OSX 上尝试过这个,它的ping
表现正如我希望的那样。)
简单的while
循环是不够的,因为 ctrl-C 处理不能正常工作。
如何ping
在 Linux 上设置即使最初没有连接也继续重试?
答案1
这是我的 Bash 解决方案,它进行了一些修改以使 Ctrl-C 按预期工作。
retry_ping() {( #run in subshell, so don't need to reset SIGINT or EXIT variable
trap "EXIT=1" SIGINT
while true; do
ping $1 &
wait
if [ $EXIT ]; then
break
fi
sleep 2 #or however long you want
done
)}
#usage example
retry_ping 8.8.8.8
或者一行:
retry_ping(){(trap "EXIT=1" SIGINT;while true;do ping $1& wait;if [ $EXIT ];then break;fi;sleep 2;done)}
示例输出:
user@machine:~$ retry_ping 8.8.8.8
connect: Network is unreachable
connect: Network is unreachable
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=120 time=5.07 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=120 time=3.04 ms
ping: sendmsg: Network is unreachable
ping: sendmsg: Network is unreachable
64 bytes from 8.8.8.8: icmp_seq=5 ttl=120 time=4.04 ms
64 bytes from 8.8.8.8: icmp_seq=6 ttl=120 time=3.10 ms
^C
--- 8.8.8.8 ping statistics ---
6 packets transmitted, 4 received, 33% packet loss, time 5109ms
rtt min/avg/max/mdev = 3.07/4.057/5.07/1.000 ms