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()
}
}
}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
