Signal Handling and Cleanup Using "Defer"
In programming, it is often desirable to perform cleanup or error-handling actions when interrupting a running process, such as when a user presses Ctrl C (SIGINT) to terminate the program. The "defer" keyword provides a convenient way to ensure that such actions are executed before the program exits.
Capturing the SIGINT Signal
To capture the SIGINT signal, you can use the os/signal package, which provides functions for handling incoming signals.
package main import ( "fmt" "os" "os/signal" ) // main function func main() { gracefulExit() } // Listen for and handle Ctrl+C (SIGINT) signal func gracefulExit() { // Create a channel to receive signals on sigs := make(chan os.Signal, 1) // Register SIGINT (Ctrl+C) signal handler signal.Notify(sigs, os.Interrupt) // Start a goroutine to listen for signals go func() { sig := <-sigs fmt.Printf("Received %v signal. Cleaning up and exiting...\n", sig) // Trigger cleanup actions using "defer" defer cleanup() defer saveResults() os.Exit(0) }() // Start running the program's main logic runProgram() }
Executing Defer Actions
Within the signal handling goroutine, before terminating the program, you can use the defer keyword to define cleanup actions that will be executed in reverse order of their declaration. In the example above, the cleanup() and saveResults() functions will be called before the program exits.
Customizing Cleanup Behavior
The actual cleanup actions that need to be performed when the SIGINT signal is received will vary depending on the program's specific needs. This flexibility makes signal handling and cleanup using "defer" a versatile and effective technique for managing unexpected interruptions in your code.
The above is the detailed content of How Can 'defer' Ensure Clean Program Exit on SIGINT Signals in Go?. For more information, please follow other related articles on the PHP Chinese website!