Home >Backend Development >Golang >How Can I Perform Cleanup Actions When a Go Program Exits?

How Can I Perform Cleanup Actions When a Go Program Exits?

Susan Sarandon
Susan SarandonOriginal
2024-12-20 04:21:12395browse

How Can I Perform Cleanup Actions When a Go Program Exits?

Performing End-of-Execution Actions in Go

In Go, you can execute specific actions when your program exits, including in response to a user-initiated interrupt (Ctrl-C). Understanding Unix signals can be helpful in these scenarios.

Catching the Interrupt Signal

To catch the interrupt signal (SIGINT), which is triggered when a user presses Ctrl-C, you can use the os.Signal and signal.Notify packages like this:

package main

import (
    "fmt"
    "os"
    "os/signal"
)

func main() {
    fmt.Println("Program started!")

    // Create a channel for receiving signals
    sigchan := make(chan os.Signal, 1)

    // Notify the channel on receipt of the interrupt signal
    signal.Notify(sigchan, os.Interrupt)

    // Start a separate goroutine to handle the interrupt signal
    go func() {
        <-sigchan
        fmt.Println("Program interrupted!")
        fmt.Println("Performing cleanup actions...")

        // Perform end-of-execution actions

        // Exit the program cleanly
        os.Exit(0)
    }()

    // Start main program tasks
}

In this example, a goroutine is launched to handle the interrupt signal. When Ctrl-C is pressed, it prints a message, performs any necessary cleanup actions (e.g., flushing buffers, closing connections), and calls os.Exit(0) to exit the program gracefully.

The above is the detailed content of How Can I Perform Cleanup Actions When a Go Program Exits?. 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