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
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go