我正在尝试在用 go 编写的命令行界面中实现一些非典型行为。
我有一个运行很长时间的函数,我想要一个清理函数,当有人 ctrl-c 退出该函数时运行。
这是代码的模型:
func longRunningFunction() {
//some set up stuff
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
fmt.Println("Got an interrupt")
cleanup()
}()
//the long-running command
fmt.Println("the end")
}
在正常情况下,不需要使用 ctrl-c,函数将正常完成。 (正因为如此,在清理 goroutine 完成之前,我不能在主线程中有阻塞的东西(比如 channel )。)但是,如果用户按下 ctrl-c,我想结束立即执行程序,而不是打印“结束”(最好不要完成长时间运行的命令)。
现在还没有发生这种情况。目前,命令行输出如下所示:
...
//long-running-command's output
^CGot an interrupt
//cleanup code's output
$
//more of long-running-command's output
the end
我在几个方面感到困惑 - 为什么程序在提示返回后仍在打印,为什么仍在打印“结尾”?我怎样才能避免这种行为?这种情况甚至可能发生吗?谢谢!
最佳答案
您将在信号处理程序之后继续执行。如果您想退出该过程,请调用 os.Exit
:
go func() {
<-sigs
fmt.Println("Got an interrupt")
cleanup()
os.Exit(2)
}()
关于go - 如何从 goroutine 结束一个 go 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42818887/