Signals in Go

Go: Signals

Signals are a way for an operating system to send notifications to a running process in Golang.

Signals can be used to perform various actions, such as stopping or restarting a process, or to trigger a specific behavior within a program

    package main

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

    func main() {
        sigs := make(chan os.Signal, 1)
        signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

        fmt.Println("Waiting for signals...")
        sig := <-sigs
        fmt.Printf("Received signal: %s\n", sig)
    }

  • In this example, we create a channel sigs of type os.Signal to receive signals from the operating system. We then use the signal.Notify function to register the sigs channel to receive SIGINT and SIGTERM signals, which are typically used to stop a process.

  • Next, we wait for a signal to be received on the sigs channel using the <- operator. When a signal is received, we print a message to the console indicating which signal was received.

Benifits of using signals in Go

By handling signals in our Go programs, you can gracefully shutdown our applications or perform specific actions when a particular signal is received. This can be useful for managing the lifecycle of our programs and ensuring that they behave correctly when interacting with the operating system.

Previous Article