douminfu8033 2017-03-15 19:21
浏览 82
已采纳

如何从goroutine结束go程序

I'm trying to implement some non-typical behavior in a command line interface written in go.

I have a function that runs for a long time, and I want to have a cleanup function that runs when someone ctrl-c's out of that function.

Here's a mock-up of the code:

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")
}

In the normal case, using ctrl-c will not be necessary and the function will finish normally. (Because of this, I can't have something (like a channel) in the main thread that blocks until the cleanup goroutine has finished.) However, in the case that a user does press ctrl-c, I would like to end the program immediately, not printing "the end" (and ideally not finishing the long-running command).

That's not happening right now. Currently, the command line output looks like this:

...
//long-running-command's output
^CGot an interrupt
//cleanup code's output
$
//more of long-running-command's output
the end

I'm confused on a few fronts - why is the program still printing after the prompt returns, and why is "the end" still being printed? How can I avoid this behavior? Is this scenario even possible in go? Thanks!

  • 写回答

1条回答 默认 最新

  • dqy0707 2017-03-15 19:26
    关注

    You're continuing execution after your signal handler. If you want to exit the process, call os.Exit:

    go func() {
        <-sigs
        fmt.Println("Got an interrupt")
        cleanup()
        os.Exit(2)
    }()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?