Last active
March 10, 2024 00:53
-
-
Save nasitra/6a1031847aaf33220dc70cefe5f8765f to your computer and use it in GitHub Desktop.
Kill child processes in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module sample | |
go 1.22.1 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"os" | |
"os/exec" | |
"os/signal" | |
"sample/task" | |
"sync" | |
"time" | |
) | |
func main() { | |
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) | |
defer stop() | |
cmd := exec.CommandContext(ctx, "bash", "-c", "yes &") | |
cmd.SysProcAttr = task.NewSysProcAttr() | |
cmd.Cancel = sync.OnceValue(func() error { | |
return task.Kill(cmd.Process.Pid) | |
}) | |
cmd.WaitDelay = 3 * time.Second | |
err := cmd.Start() | |
if err != nil { | |
fmt.Fprintln(os.Stderr, err) | |
return | |
} | |
time.Sleep(5 * time.Second) | |
err = cmd.Cancel() | |
if err != nil { | |
fmt.Fprintln(os.Stderr, err) | |
} | |
cmd.Wait() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//go:build !windows && (linux || darwin) | |
package task | |
import "syscall" | |
func NewSysProcAttr() *syscall.SysProcAttr { | |
return &syscall.SysProcAttr{Setpgid: true} | |
} | |
func Kill(pid int) error { | |
return syscall.Kill(-pid, syscall.SIGKILL) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package task | |
import ( | |
"os/exec" | |
"strconv" | |
"syscall" | |
) | |
func NewSysProcAttr() *syscall.SysProcAttr { | |
return nil | |
} | |
func Kill(pid int) error { | |
return exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment