我无法正常退出我自己的 Windows go 程序。 os.Interrupt 似乎也不起作用。我想知道有没有办法在终端中优雅地退出golang程序?
func main() {
sigs := make(chan os.Signal, 1)
done := make(chan bool, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
fmt.Println()
fmt.Println(sig)
done <- true
}()
fmt.Println("awaiting signal")
<-done
fmt.Println("exiting")
}
最佳答案
您的代码运行良好,程序正常退出,我在 Windows 命令提示符下对其进行了测试。
为了更加说服你,试着加上time.Sleep(5 * time.Second)
在 <-done
之后,然后测试。当你中断它时,程序只会在 5 秒后关闭。
fmt.Println("awaiting signal")
<-done
fmt.Println("exiting in 5 seconds")
time.Sleep(5 * time.Second)
fmt.Println("exit success")
也像@ain 在评论中所说的那样,尝试添加 os.Interrupt
在 signal.Notify
signal.Notify(sigs, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
关于windows - 在终端的 Windows 中优雅地退出 golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57213146/