Go by Example: Signals

In Go, signals are a form of interrupt delivered to a running process. Go provides support for handling signals through the os/signal package. The following example demonstrates how to catch interrupt signals and shutdown gracefully:

package main

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

func main() {
	sigs := make(chan os.Signal, 1)
	done := make(chan bool, 1)

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

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

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

This example sets up a channel sigs to receive interrupt signals and a channel done to notify the main goroutine when a signal is received. The signal.Notify function is used to specify which signals to receive (SIGINT and SIGTERM in this case). The main function waits for a signal to be received on the sigs channel and prints it. Once a signal is received, the done channel is closed to notify the main goroutine that it’s time to exit.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *