Files
ThothII/tools/tht/internal/compose/process_windows.go
T

57 lines
1.3 KiB
Go

//go:build windows
package compose
import (
"context"
"io"
"os/exec"
"strconv"
"syscall"
"time"
)
const finalTerminationBound = 2 * time.Second
const processTreeTerminationBound = 2 * time.Second
const createNewProcessGroup = 0x00000200
func configureProcess(command *exec.Cmd) {
command.SysProcAttr = &syscall.SysProcAttr{CreationFlags: createNewProcessGroup}
}
func terminateProcess(command *exec.Cmd, done <-chan error) error {
if command.Process == nil {
return nil
}
treeErr := terminateWindowsProcessTree(command.Process.Pid)
_ = command.Process.Kill()
select {
case <-done:
if treeErr != nil {
return ErrProcessReap
}
return nil
case <-time.After(finalTerminationBound):
return ErrProcessReap
}
}
func terminateWindowsProcessTree(pid int) error {
ctx, cancel := context.WithTimeout(context.Background(), processTreeTerminationBound)
defer cancel()
command := windowsTreeKillCommand(ctx, pid)
command.Stdout = io.Discard
command.Stderr = io.Discard
if err := command.Run(); err != nil {
return ErrProcessReap
}
if ctx.Err() != nil {
return ErrProcessReap
}
return nil
}
func windowsTreeKillCommand(ctx context.Context, pid int) *exec.Cmd {
return exec.CommandContext(ctx, "taskkill.exe", "/PID", strconv.Itoa(pid), "/T", "/F")
}