Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Golang, how to terminate an os.exec.Cmd process with a SIGTERM instead of a SIGKILL?

Currently, I am terminating a process using the Golang os.exec.Cmd.Process.Kill() method (on an Ubuntu box).

This seems to terminate the process immediately instead of gracefully. Some of the processes that I am launching also write to files, and it causes the files to become truncated.

I want to terminate the process gracefully with a SIGTERM instead of a SIGKILL using Golang.

Here is a simple example of a process that is started and then terminated using cmd.Process.Kill(), I would like an alternative in Golang to the Kill() method which uses SIGTERM instead of SIGKILL, thanks!

import "os/exec"

cmd := exec.Command("nc", "example.com", "80")
if err := cmd.Start(); err != nil {
   log.Print(err)
}
go func() {
  cmd.Wait()
}()
// Kill the process - this seems to kill the process ungracefully
cmd.Process.Kill()
like image 406
Evyatar Saias Avatar asked Sep 12 '25 01:09

Evyatar Saias


1 Answers

You can use Signal() API. The supported Syscalls are here.

So basically you might want to use

cmd.Process.Signal(syscall.SIGTERM)

Also please note as per documentation.

The only signal values guaranteed to be present in the os package on all systems are os.Interrupt (send the process an interrupt) and os.Kill (force the process to exit). On Windows, sending os.Interrupt to a process with os.Process.Signal is not implemented; it will return an error instead of sending a signal.

like image 159
Shailesh Suryawanshi Avatar answered Sep 13 '25 17:09

Shailesh Suryawanshi