-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexec_windows.go
More file actions
71 lines (65 loc) · 1.76 KB
/
Copy pathexec_windows.go
File metadata and controls
71 lines (65 loc) · 1.76 KB
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
//go:build windows
package main
import (
"fmt"
"os/exec"
"strconv"
"strings"
"syscall"
)
func setProcessGroup(cmd *exec.Cmd) {
// Windows: process group kill is done via taskkill /T
}
func killProcessGroup(pid int) error {
// /T = kill child processes too
out, err := exec.Command("taskkill", "/PID", strconv.Itoa(pid), "/T", "/F").CombinedOutput()
if err != nil {
return fmt.Errorf("%s", string(out))
}
return nil
}
func isProcessAlive(pid int) bool {
kernel32 := syscall.NewLazyDLL("kernel32.dll")
openProcess := kernel32.NewProc("OpenProcess")
// PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
h, _, _ := openProcess.Call(0x1000, 0, uintptr(pid))
if h == 0 {
return false
}
syscall.CloseHandle(syscall.Handle(h))
return true
}
func killPort(rawURL string) (string, error) {
port := portFromURL(rawURL)
if port == "" {
return "", fmt.Errorf("could not extract port from URL")
}
out, err := exec.Command("netstat", "-ano").Output()
if err != nil {
return "", fmt.Errorf("netstat: %w", err)
}
var pids []string
seen := make(map[string]bool)
for _, line := range strings.Split(string(out), "\n") {
line = strings.TrimSpace(line)
if !strings.Contains(line, ":"+port) || !strings.Contains(line, "LISTENING") {
continue
}
fields := strings.Fields(line)
if len(fields) < 5 {
continue
}
pid := fields[len(fields)-1]
if pid != "0" && !seen[pid] {
seen[pid] = true
pids = append(pids, pid)
}
}
if len(pids) == 0 {
return "", fmt.Errorf("no process found on port %s", port)
}
for _, p := range pids {
exec.Command("taskkill", "/PID", p, "/F").Run()
}
return fmt.Sprintf("killed %d process(es) on port %s (PIDs: %s)", len(pids), port, strings.Join(pids, ", ")), nil
}