Capturing Ctrl C for Cleanup Operations: A "Defer" Approach
Handling signals in Go allows developers to respond to specific events, including the termination of a program. One common scenario is capturing the Ctrl C (SIGINT) signal to perform any necessary cleanup operations before the program exits.
Creating a Channel for Signal Handling
To capture the SIGINT signal, we utilize the os/signal package. First, we create a channel to receive signals:
c := make(chan os.Signal, 1)
Subscribing to the Ctrl C Signal
Next, we notify the channel to listen for the SIGINT signal:
signal.Notify(c, os.Interrupt)
Initiating a Goroutine for Signal Handling
We create a goroutine to handle signals continuously:
go func(){ for sig := range c { // sig is a ^C, handle it } }()
Performing Cleanup Operations
Within the goroutine, we can define the cleanup operations to be performed when Ctrl C is pressed. This could include writing data to disk, saving preferences, or any other task that should be completed before the program exits.
The manner in which you cause your program to terminate and print information based on the Ctrl C input is flexible and depends on the specific requirements of your program.
The above is the detailed content of How Can I Gracefully Handle Ctrl C Signals in Go for Clean Program Termination?. For more information, please follow other related articles on the PHP Chinese website!