Golang – kill process by name

Issue

What would be an effective way to kill a process with Go code if you only know the process name? I see some functions provided by the os package like:

func FindProcess(pid int) (*Process, error)
func (p *Process) Kill() error
func (p *Process) Signal(sig Signal) error

Is there a good/common practice to get the pid without having to execute commands and then parse the output?

I have found a way to get back the pid using a command like the following:

  • echo $(ps cax | grep myapp | grep -o '^[ ]*[0-9]*')

and I have used it with exec.Command() but I would like to avoid it if there is a better approach.

Solution

I finally used something like the following:

// `echo "sudo_password" | sudo -S [command]`
// is used in order to run the command with `sudo`

_, err := exec.Command("sh", "-c", "echo '"+ sudopassword +"' | sudo -S pkill -SIGINT my_app_name").Output()

if err != nil {
    // ...
} else {
    // ...
}

I used the SIGINT signal to gracefully stop the app.

From wikipedia:

  • SIGINT

    The SIGINT signal is sent to a process by its controlling terminal when a user wishes to interrupt the process. This is typically initiated by pressing Ctrl+C, but on some systems, the “delete” character or “break” key can be used.

  • SIGKILL

    The SIGKILL signal is sent to a process to cause it to terminate immediately (kill). In contrast to SIGTERM and SIGINT, this signal cannot be caught or ignored, and the receiving process cannot perform any clean-up upon receiving this signal. The following exceptions apply:

Answered By – tgogos

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.