Executing Operations After Exiting a Go Program
Question:
How can one execute specific operations at the end of a Go program's execution? This is particularly relevant for handling cleanup tasks or graceful exits in HTTP servers.
Answer:
Utilizing Unix Signals
Handling end-of-execution actions in Go involves registering for Unix signals, such as SIGINT (generated by Ctrl-C). This signal notifies the Go runtime when the program should be terminated.
Code Snippet
The following code snippet demonstrates how to catch the interrupt signal and perform cleanup operations before exiting:
package main import ( "log" "os" "os/signal" ) func main() { // Create a channel to receive the interrupt signal. sigchan := make(chan os.Signal) signal.Notify(sigchan, os.Interrupt) // Start a goroutine to listen for the signal. go func() { <-sigchan log.Println("Program killed!") // Perform last actions and wait for all write operations to end. os.Exit(0) }() // Start the main program tasks. }
Explanation
The above is the detailed content of How Can I Execute Cleanup Operations Before a Go Program Exits?. For more information, please follow other related articles on the PHP Chinese website!