【发布时间】:2017-08-06 17:32:12
【问题描述】:
我正在尝试在用 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 完成之前,我不能在主线程中有阻塞的东西(比如通道)。)但是,如果用户确实按下 ctrl-c,我想结束立即编程,不打印“结束”(理想情况下不完成长时间运行的命令)。
现在还没有发生。目前,命令行输出如下所示:
...
//long-running-command's output
^CGot an interrupt
//cleanup code's output
$
//more of long-running-command's output
the end
我在几个方面感到困惑 - 为什么在提示返回后程序仍在打印,为什么仍在打印“结束”?我怎样才能避免这种行为?这种情况甚至可能在go中出现吗?谢谢!
【问题讨论】:
标签: go command-line-interface channel goroutine