Search code examples
multithreadinggogoroutine

Go server hangs after sending INT signal


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!


Solution

  • 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.