package main import ( "os" "os/signal" "syscall" ) func main() { // Create a channel to receive signals sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) // Block until a signal is received <-sigs // Shutdown gracefully shutdown() } func shutdown() { // Perform any necessary clean-up actions // before shutting down the program }
package main import ( "os" "os/signal" "syscall" ) func main() { // Create a channel to receive signals sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGHUP) for { log.Println("Listening for SIGHUP...") // Block until a SIGHUP signal is received <-sigs // Restart the program restart() } } func restart() { // Perform any necessary clean-up actions // before restarting the program // ... // Execute the program again with the same arguments execFile, _ := os.Executable() args := os.Args[1:] syscall.Exec(execFile, args, os.Environ()) }This code sets up a loop to listen for the SIGHUP signal, which is commonly used for reloading configuration files or restarting servers. When a SIGHUP signal is received, the program initiates a restart by calling the `restart()` function. In both examples, the `os/signal` package is used to notify the program of specific signals and handle them appropriately.