我有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上ping。查看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()
}
打印结果时(添加'结果'在功能内)
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中很好)
答案 0 :(得分:1)
您可能会忽略恐慌,将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)
}
}
这应该打印恐慌,如果它发生,以及保证调用wg.Done()
//注意:没有运行这个,但它的方向是正确的