In Go, you can send and receive signals to/from processes using the os/signal
package and syscall
package. Here's how you can do it:
To send a signal to a process:
import (
"syscall"
"os"
"os/signal"
)
syscall.Getpid()
function to get the PID of the current process.syscall.Kill()
function to send the signal to the target process:targetPID := 1234 // Replace with the target process ID
signalToSend := syscall.SIGTERM // Replace with the desired signal
err := syscall.Kill(targetPID, signalToSend)
if err != nil {
log.Fatal(err)
}
To receive signals in a process:
import (
"os"
"os/signal"
"syscall"
)
signalChannel := make(chan os.Signal, 1)
SIGINT
, SIGTERM
) and register the channel to receive them:signal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM)
go func() {
for {
receivedSignal := <-signalChannel
// Handle the received signal
// For example, you can print a message or perform cleanup actions:
log.Printf("Received signal: %s", receivedSignal.String())
// Terminate the program gracefully
os.Exit(0)
}
}()
Note: It's important to handle signals properly to avoid unexpected termination or undesirable behavior in your program. Make sure to handle signals in a way that gracefully terminates your program or performs necessary cleanup actions.
Check the documentation for more information:
os/signal
: https://golang.org/pkg/os/signal/syscall
: https://golang.org/pkg/syscall/