duan2891 2017-10-23 10:21
浏览 22
已采纳

发送INT信号后Go服务器挂起

Here is the code:

package main

import (
    "log"
    _ "net/http/pprof"
    "fmt"
    "net/http"
    "html"
    "os/signal"
    "os"
)

func main() {
//INT signal handling
    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt)
    go func() {
        for range c {
            log.Println("GOT SIGNAL!")
            return

        }
    }()
//INT signal handling

    http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}

After pressing CTRL-C it hangs (server keeps working). But if you comment block between "INT signal handling", it finishes fine. Could you please explain this behaviour? It's obvious that http server can be created and started explicitly in separate goroutine and gracefully terminated there. But in general the question is how to explain behaviour from this code snipped, why http does not stop if there is new channel that handles SIGNTERM. Thank you!

  • 写回答

1条回答 默认 最新

  • doudu161481 2017-10-23 10:44
    关注

    In your INT handler you do not quit the program yourself.

    If you install a signal handler for INT the default behavior of the program on receiving a Ctrl+C, which is quit the program, is not done. Instead the program now handles it by calling your INT handler code instead so if you want to exit your program, call os.Exit(0) in the loop.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类