我有ping功能,可以在Windows上正常工作,但在Linux上無法正常工作。在Linux上,它會ping幾個主機並停止(不退出)。golang sync.WaitGroup在Linux上沒有完成
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()
}
當打印結果(添加「結果」 FUNC平內)
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中很好)
你在哪裏添加和從WaitGroup中刪除的東西? – JimB
如果你正在goroutine本身中添加waitGroup,這可能會發生。 –
我正在爲main()中的循環添加'wg.Add(len(hosts))'。永遠不要刪除任何東西,因爲在循環之後有'wg.Wait()' – irom