Handling Interrupt Signals in Go for a Graceful Shutdown
When running a Go program, interrupt signals like Ctrl+C (SIGINT) or kill (SIGTERM) can abruptly terminate the process, potentially leading to data loss or unclean exits. To prevent this, we can catch these signals and perform cleanup before exiting.
Here’s a simple Go program that handles SIGINT, SIGTSTP, SIGTERM, and SIGHUP, ensuring a graceful shutdown:
switch signalData { case syscall.SIGINT: fmt.Println("Ctrl+C pressed. Exiting gracefully...") case syscall.SIGTSTP: fmt.Println("Ctrl+Z pressed. Suspending process...") case syscall.SIGTERM: fmt.Println("Termination signal received. Cleaning up...") case syscall.SIGHUP: fmt.Println("Terminal closed or Parent process killed. Handling reconnect...") }
fmt.Println("Signal handled. Process exited cleanly.") }
How It Works
The program listens for termination signals using signal.Notify().
When a signal is received, it logs the signal, runs cleanup operations, and exits gracefully.
Why It Matters
Without handling signals, the process would terminate abruptly, potentially leaving database connections open or unsaved work lost. Adding a graceful shutdown ensures a smooth exit.
Now, whenever you press Ctrl+C or send a termination signal, your program will handle it properly! 🚀