关闭进程
参考文档: https://stackoverflow.com/questions/11886531/terminating-a-process-started-with-os-exec-in-golang
cmd.Process.Kill()
// Start a process:
cmd := exec.Command("sleep", "5")
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
// Kill it:
if err := cmd.Process.Kill(); err != nil {
log.Fatal("failed to kill process: ", err)
}
超时Kill进程
Run and terminate an exec.Process
after a timeout:
ctx, cancel := context.WithTimeout(context.Background(), 3 * time.Second)
defer cancel()
if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {
// This will fail after 3 seconds. The 5 second sleep
// will be interrupted.
}
示例:
package main
import (
"context"
"os"
"os/exec"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "sleep", "5")
cmd.Stdout = os.Stdout
cmd.Dir = "/root"
err := cmd.Run()
if err != nil {
panic(err)
}
}
输出:
panic: signal: killed
goroutine 1 [running]:
main.main()
test/main.go:19 +0x157
exit status 2
Before Go 1.7
Before Go 1.7, we didn’t have the context
package and this answer was different.
Run and terminate an exec.Process
after a timeout using channels and a goroutine:
// Start a process:
cmd := exec.Command("sleep", "5")
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
// Wait for the process to finish or kill it after a timeout (whichever happens first):
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case <-time.After(3 * time.Second):
if err := cmd.Process.Kill(); err != nil {
log.Fatal("failed to kill process: ", err)
}
log.Println("process killed as timeout reached")
case err := <-done:
if err != nil {
log.Fatalf("process finished with error = %v", err)
}
log.Print("process finished successfully")
}
Either the process ends and its error (if any) is received through done
or 3 seconds have passed and the program is killed before it’s finished.