我试图在用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的情况下,我想结束立即执行程序,而不打印“the end”(理想情况下不完成长时间运行的命令)。

现在还没有发生。当前,命令行输出如下所示:
...
//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)
}()

10-06 09:15