Golang / GoLang Production Patterns and Web Standards Interview Questions
How do Go programs handle OS signals and interact with the operating system?
Go programs receive OS signals through the os/signal package. Signals are delivered to Go channels via signal.Notify. Common production uses: graceful shutdown (SIGTERM), config reload (SIGHUP), and heap dump triggering (SIGUSR1).
import ( "os" "os/signal" "syscall" ) // Standard graceful shutdown func waitForShutdown(srv *http.Server, cleanup func()) { quit := make(chan os.Signal, 1) // Always use a buffered channel â avoid missing a signal if handler is slow signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) defer signal.Stop(quit) // unregister when function exits <-quit log.Println("shutdown signal received") ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() srv.Shutdown(ctx) cleanup() } // SIGHUP: reload configuration without restart func watchConfigReload(cfg *atomic.Pointer[Config]) { reload := make(chan os.Signal, 1) signal.Notify(reload, syscall.SIGHUP) for range reload { newCfg, err := loadConfig() if err != nil { log.Printf("config reload failed: %v", err) continue } cfg.Store(newCfg) log.Println("configuration reloaded") } } // Multiple signals: select over several signal channels func signalRouter() { sigint := make(chan os.Signal, 1) sigusr1 := make(chan os.Signal, 1) signal.Notify(sigint, syscall.SIGINT, syscall.SIGTERM) signal.Notify(sigusr1, syscall.SIGUSR1) for { select { case <-sigint: initiateShutdown(); return case <-sigusr1: dumpHeapProfile() } } }
More Related questions...