Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

1 snippets
  • Handle OS signals in Go

    package main
    
    import (
        "fmt"
        "os"
        "os/signal"
        "syscall"
    )
    
    func main() {
        sigs := make(chan os.Signal, 1) // create channel for signal, it should be buffered
        signal.Notify(sigs, syscall.SIGINT) // register the channel to receive notifications of the specified signals
        done := make(chan bool, 1)
    
        go func() {
            sig := <-sigs // wait for OS signal, once received, notify main go routine
            fmt.Printf("\nos signal: %v\n", sig)
            done <- true
        }()
    
        fmt.Println("awaiting signal")
        <-done // wait for the expected signal and then exit
        fmt.Println("exiting")
    }
    
    // $ go run main.go 
    // awaiting os signal
    // ^C
    // os signal: interrupt
    // exiting program

    Here is an example go program for processing Unix signals using channels. Signal processing can be useful, for example, for correct terminating of program when receiving SIGTINT.