我有 ping 功能,它在 Windows 上运行良好,但在 Linux 上却不行。在 Linux 上,它会 ping 几台主机并停止(不退出)。
func main() {
...
wg.Add(len(hosts))
for _, ip := range hosts {
go ping(ip, &wg, os)
}
wg.Wait()
...
}
我可以在 Windows 上 ping 数百台主机,但在 Linux 上不行。看https://github.com/irom77/go-public/blob/master/gping/main.go对于整个事情
func ping(ip string, wg *sync.WaitGroup, os string ) {
_ , err := exec.Command("ping", os, *PINGCOUNT, "-w", *PINGTIMEOUT, ip).Output()
if err == nil {
count++
fmt.Printf("%d %s \n", count, ip)
}
wg.Done()
}
打印结果时(在func ping中添加'result')
result , err := exec.Command("ping", os, *PINGCOUNT, "-w", *PINGTIMEOUT, ip).Output()
fmt.Printf("%s\n", result)
我刚得到正确的输出,但它没有继续 ping 下一个 IP
....
--- 10.192.167.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 476.564/476.564/476.564/0.000 ms
49 10.192.167.1
在这里期待更多的 IP(在 Windows 中很好)
最佳答案
您可能会忽略这里的 panic ,将您的 ping 函数更改为:
func ping(ip string, wg *sync.WaitGroup, os string ) {
defer wg.Done()
defer func(){
if err := recover(); err != nil {
fmt.Println("Error with:",ip,"err:",err)
}
}()
result , err := exec.Command("ping", os, *PINGCOUNT, "-w", PINGTIMEOUT, ip).Output()
fmt.Printf("%s\n", result)
if err == nil {
count++
fmt.Printf("%d %s \n", count, ip)
} else {
//fmt.Printf("%s is dead\n", ip)
}
}
这应该打印 panic ,如果它发生,以及保证调用 wg.Done()
//注意:没有运行这个,但是它的方向是正确的
关于golang sync.WaitGroup 在 Linux 上没有完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40049884/