How to terminate a running Golang process using the os package?

To terminate a running Golang process programmatically using the os package, you can use the os.Exit() function. Here's an example:

package main import ( "fmt" "os" "os/signal" "syscall" ) func main() { // Create a channel to listen for termination signals sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM) // Start a goroutine to wait for the termination signal go func() { sig := <-sigChan fmt.Printf("Received termination signal: %v\n", sig) // Terminate the process os.Exit(0) }() // Simulate a long-running process for { // Do some work here... } }

In this example, we create a channel (sigChan) to listen for termination signals (os.Interrupt and syscall.SIGTERM). We use the signal.Notify() function to register the channel to receive these signals.

Next, we start a goroutine that waits for the termination signal. When a signal is received, the goroutine will print a message and call os.Exit(0) to terminate the process with an exit code of 0.

The main goroutine then enters an infinite loop to simulate a long-running process.