Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Go by Example https://gobyexample.com/signals


package main import ( "fmt" "os" "os/signal" "syscall" ) func main() { sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) done := make(chan bool, 1) go func() { sig := <-sigs fmt.Println() fmt.Println(sig) done <- true }() fmt.Println("awaiting signal") <-done fmt.Println("exiting") }
Code Block
languagecpp
package main

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

func main() {

    sigs := make(chan os.Signal, 1)

    signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

    done := make(chan bool, 1)

    go func() {

        sig := <-sigs
        fmt.Println()
        fmt.Println(sig)
        done <- true
    }()

    fmt.Println("awaiting signal")
    <-done
    fmt.Println("exiting")
}
Code Block


Another Example:


Code Block
package main
import (
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	
	//create channel that can receive OS signals
	ch := make(chan os.Signal)

    //Submit channel to the notify signal
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT)


	//a go function to monitor signals in the background
	go func() {
		for sig := range ch {
			switch sig {
			case syscall.SIGTERM:
				fmt.Println("sigterm received')
				os.Exit(0)
			case syscall.SIGINT:
				fmt.Println("sigint received')
				oS.Exit(0)
			}
		}
	}()

	time.Sleep(time.Minute)
}

...