go - 如何从 goroutine 结束一个 go 程序

标签 go command-line-interface channel goroutine

我正在尝试在用 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/

相关文章:

node.js - NG Live Development Server 与传统 Web 服务器

Java 选择器在接受连接后卡在 select() 上

ios - 为什么许多音频播放器将我的单声道 AAC (m4a) 文件解释为立体声?

用于列出已执行测试的 PHPUnit 配置选项

android - channel 不可恢复地损坏,将被处理掉

不同类型的Golang接口(interface)——传值时的困惑

Go语言如何检测文件变化?

performance - 可变参数函数在 Go 中导致不必要的堆分配

google-chrome-extension - 全局键盘输入去

php - 当您从 CLI 中按 ctrl + c 时,PHP 进程会退出吗?