Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process.Kill() on child processes

Tags:

go

I'm trying to stop the process started with exec.Command("go", "run", "server.go") and all its child processes.

But when I call cmd.Process.Kill() and the go process stops, the child process (a web server in server.go) continues to run.

package main

import (
    "fmt"
    "os/exec"
    "time"
)

func run() *exec.Cmd {
    cmd := exec.Command("go", "run", "server.go")

    err := cmd.Start()
    if err != nil {
        panic(err)
    }

    return cmd
}

func main() {
    cmd := run()

    time.Sleep(time.Second * 2)

    err := cmd.Process.Kill()
    if err != nil {
        panic(err)
    }
    cmd.Process.Wait()

    // === Web server is still running! ===

    fmt.Scanln()
}

It looks like Process.Kill() only stops the go (run) process, but leaves its child process (web server) running.

^C kills the whole process group, including all child (and sub-child) processes. How can I do the same?

I tried cmd.Process.Signal(os.Interrupt), syscall.SIGINT, syscall.SIGQUIT and syscall.SIGKILL, none of which did anything.

like image 239
bernhardw Avatar asked Jul 27 '14 16:07

bernhardw


1 Answers

Don't use the go run command. Use the go install command to install your packages and programs and then execute your program.

like image 184
peterSO Avatar answered Nov 15 '22 04:11

peterSO