我遇到了一个Go程序的问题,该程序应该能够捕获SIGTERM并正常关闭。我可以看到它启动了关机过程,但随后它突然退出,没有完成关机过程。我在不同的地方放置了一些日志,可以看到它们没有将任何内容打印到stdout。以下是代码片段和结果:

    sigs := make(chan os.Signal, 1)
    signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)

    select {
    case <-sigs:
        signal.Stop(sigs)
        log.Info().Msg("runsomething: SIGTERM caught")
        close(stopC)
        cancel()
        log.Info().Msg("Stopping all goroutines")

        // This sleep doesn't have any effect when shutdown via SIGTERM
        time.Sleep(time.Second * 2)
        log.Info().Msg("THIS SHOULD PRINT, WHY DOESNT IT?")
    case <-doneC:
    }

    // This sleep doesn't have any effect when shutdown via SIGTERM nor
    // does the following log print
    time.Sleep(time.Second * 2)
    log.Info().Msg("runsomething: DONE")

下面是正常完成的结果:

./runsomething             
May  5 09:46:35.000 INF runsomething started 
May  5 09:46:37.000 INF Summarizing results and exiting
May  5 09:46:37.000 INF Run results COMPLETED
May  5 09:46:39.000INF runsomething: DONE

以下是中断的结果:

May  5 09:39:48.000 INF runsomething started
^CMay  5 09:39:50.000 INF runsomething: SIGTERM caught
May  5 09:39:50.000 INF Stopping all goroutines
May  5 09:39:50.000 INF GracefulShutdown: Started

有几个缺失的输出行。给出上面的代码片段,我希望看到:

...continued from above...
May  5 09:39:50.000 INF THIS SHOULD PRINT, WHY DOESNT IT? The sleep below also isn't run?
May  5 09:39:50.000 INF GracefulShutdown: Completed
May  5 09:39:50.000 INF runsomething: DONE
time.Sleep()GracefulShutdown: Started
fmt.Printf[]byte
    rsjson, err := json.Marshal(runSummary)
    if err != nil {
        log.Error().Err(err).Msgf("error marshaling RunSummary into string: %+v.\n")
        return
    }

    // TODO: debug stuff, only the printf should remain
    log.Info().Msgf("Run results: \n\n%s\n", rsjson)
    // TODO Removed Printf to see if it makes a difference
    // fmt.Printf("%s\n", string(rsjson))
    log.Info().Msgf("Run results COMPLETED")