How to send and receive signals to/from processes using syscall in Golang?

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:

  1. Import the necessary packages:
import ( "syscall" "os" "os/signal" )
  1. Get the process ID (PID) of the target process. You can use the syscall.Getpid() function to get the PID of the current process.
  2. Use the 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:

  1. Import the necessary packages:
import ( "os" "os/signal" "syscall" )
  1. Create a channel to receive the signals:
signalChannel := make(chan os.Signal, 1)
  1. Specify the signals you want to capture (e.g., SIGINT, SIGTERM) and register the channel to receive them:
signal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM)
  1. Use a goroutine to continually receive signals from the channel:
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) } }()
  1. Your program will now listen for the specified signals and perform the necessary actions when received.

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/