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.
Don't use the go run
command. Use the go install
command to install your packages and programs and then execute your program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With