Home >Backend Development >Golang >Can Go's `defer` Function Handle SIGINT for Clean Program Termination?

Can Go's `defer` Function Handle SIGINT for Clean Program Termination?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 04:54:12675browse

Can Go's `defer` Function Handle SIGINT for Clean Program Termination?

Trapping SIGINT with Defer Functions

Question: Is it possible to handle the Ctrl C (SIGINT) signal and execute a cleanup function before program termination?

Answer:

Yes, you can capture the SIGINT signal and execute a cleanup function in a "defer" fashion using the os/signal package in Go.

The signal.Notify function allows you to register a channel to receive notifications about specific signals, such as os.Interrupt (which represents the SIGINT signal generated by Ctrl C):

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)

Next, start a goroutine that waits for incoming signals:

go func(){
    for sig := range c {
        // Handle the sig interruption
    }
}()

Inside the goroutine, you can perform any necessary cleanup actions when the SIGINT signal is received.

The manner in which you terminate the program and print information is determined by your specific implementation. You have complete control over how the cleanup function operates and what actions it performs.

The above is the detailed content of Can Go's `defer` Function Handle SIGINT for Clean Program Termination?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn