-
Notifications
You must be signed in to change notification settings - Fork 0
/
subprocess_windows.go
87 lines (73 loc) · 1.98 KB
/
subprocess_windows.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//go:build windows
// Copyright 2023 Kirill Scherba <kirill@scherba.ru>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Subprocess go package used to Kills process and all child processes it
// spawned in Linux or Windows.
package subprocess
import (
"syscall"
"unsafe"
)
// KillProcessTree Kills the process and all its children in Windows
func KillProcessTree(pid int) (err error) {
// Open a handle to the process with PROCESS_TERMINATE access
handle, err := syscall.OpenProcess(syscall.PROCESS_TERMINATE, false, uint32(pid))
if err != nil {
return
}
defer syscall.CloseHandle(handle)
// Get the list of child process IDs
pids, err := getProcessChildren(pid)
if err != nil {
return
}
// Kill the child processes first
for _, childPid := range pids {
if err = KillProcessTree(childPid); err != nil {
return
}
}
// Kill the process
if err = syscall.TerminateProcess(handle, 0); err != nil {
return
}
return
}
// getProcessChildren gets the list of child process IDs
func getProcessChildren(pid int) (pids []int, err error) {
// Create a snapshot of the process list
snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
if err != nil {
return
}
defer syscall.CloseHandle(snapshot)
// Get the first process in the list
var procEntry syscall.ProcessEntry32
procEntry.Size = uint32(unsafe.Sizeof(procEntry))
err = syscall.Process32First(snapshot, &procEntry)
if err != nil {
return
}
// Find the parent process and its children
for {
if procEntry.ProcessID == uint32(pid) {
// Found the parent process, add its children to the list
for {
err := syscall.Process32Next(snapshot, &procEntry)
if err != nil {
break
}
if procEntry.ParentProcessID == uint32(pid) {
pids = append(pids, int(procEntry.ProcessID))
}
}
break
}
err = syscall.Process32Next(snapshot, &procEntry)
if err != nil {
return
}
}
return
}