为什么ping终止后还有输出?

为什么ping终止后还有输出?

据我所知,当进程中断时,将不再返回任何输出。但在破坏ping命令之后,我们总是会得到执行的统计数据,据我所知,它是输出的一部分。

amirreza@time:~$ ping 4.2.2.4
PING 4.2.2.4 (4.2.2.4) 56(84) bytes of data.
64 bytes from 4.2.2.4: icmp_seq=1 ttl=51 time=95.8 ms
64 bytes from 4.2.2.4: icmp_seq=2 ttl=51 time=92.3 ms
^C
--- 4.2.2.4 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1002ms
rtt min/avg/max/mdev = 92.321/94.052/95.783/1.731 ms
amirreza@time:~$ 

它是如何工作的?

答案1

Ctrl+C使终端向前台进程组发送SIGINT。接收到 SIGINT 的进程可以做任何事情,甚至可以忽略该信号。对 SIGINT 的常见反应是优雅退出,即在清理等之后。

你的ping简直就是设计的在 SIGINT 时打印统计信息,然后退出。

其他工具可能会也可能不会在 SIGINT 时退出。例如,交互式 shell(在不运行命令时)的通常行为是清除其命令行并重新绘制提示符。

SIGINT 并不是唯一设计用于终止命令的信号。请参阅手册(man 7 signal),有许多信号的默认操作是终止进程。kill默认发送 SIGTERM。 SIGTERM 不是 SIGINT。两者都可以忽略。SIGKILL 无法被捕获、阻止或忽略,但这应该是你最后的选择。

答案2

除了已接受的答案之外 - 这是在一个会话中运行的 ping,而在另一个会话中我运行了不同的终止命令。

server~ $ ping google.com
PING google.com (172.217.5.110) 56(84) bytes of data.
64 bytes from google.com(172.217.5.110): icmp_seq=1 ttl=111 time=1.68 ms
64 bytes from google.com(172.217.5.110): icmp_seq=2 ttl=111 time=1.73 ms
Terminated

上面是一个信号术语,这是信号 15。退出代码是 143。

server ~ $ ping google.com
PING google.com (172.217.5.110) 56(84) bytes of data.
64 bytes from google.com(172.217.5.110): icmp_seq=1 ttl=111 time=1.71 ms
64 bytes from google.com(172.217.5.110): icmp_seq=2 ttl=111 time=1.71 ms
Killed

这是一个信号杀死,即信号 9。从视觉上看,它看起来相同,但文本不同,这次退出代码是 137。

server~ $ ping google.com
PING google.com (172.217.5.110) 56(84) bytes of data.
64 bytes from google.com(172.217.5.110): icmp_seq=1 ttl=111 time=1.69 ms
64 bytes from google.com(172.217.5.110): icmp_seq=2 ttl=111 time=1.70 ms
           **signal sent here**
--- google.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 1.697/1.701/1.705/0.004 ms

这是一个信号情报这是信号 2。所以功能上与 a 相同。^C奇怪的是,退出代码是 0,对于大多数测试来说,这将是成功的,而不是失败。

这样做的结果是ping针对不同的信号执行不同的操作。

您可以在以下位置查看 ping 的源文件https://gist.github.com/kbaribeau/4495181哪些参考文献https://ftp.arl.army.mil/~mike/ping.html 和原来一样。

line
408     signal( SIGINT, finish );
409     signal(SIGALRM, catcher);

457     *           C A T C H E R
459     * This routine causes another PING to be transmitted, and then
460     * schedules another SIGALRM for 1 second from now.

请参阅链接以获取完整代码。

相关内容