-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproc.go
76 lines (70 loc) · 1.86 KB
/
proc.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
package main
import (
"encoding/csv"
"fmt"
"log"
"os/exec"
"strconv"
"strings"
)
type Pid int
func findByTitle(processTitle string) Pid {
pId := 0
if strings.TrimSpace(processTitle) != "" {
filterQuery := fmt.Sprintf("WINDOWTITLE eq %s", processTitle)
stdout, err := exec.Command("cmd", "/C", "tasklist", "/FI", filterQuery, "/FO", "CSV", "/NH").CombinedOutput()
if err != nil {
log.Fatal("❌ Unable to start tasklist command", err)
} else {
csvReader := csv.NewReader(strings.NewReader(string(stdout[:])))
records, err := csvReader.ReadAll()
if err != nil {
log.Fatal("❌ Unable to parse file as CSV", err)
}
if len(records) > 1 {
log.Fatal("❌ Found more than one process with window title", processTitle)
}
if len(records) == 1 {
line := records[0]
if len(line) >= 2 {
processIdStr := line[1]
var err error
pId, err = strconv.Atoi(processIdStr)
if err != nil {
log.Fatal("❌ Unable to fetch pId from tasklist", err)
}
if pId > 0 {
logInfo("ℹ️ Found already running process with id %d. Not starting a new process", pId)
}
}
}
}
}
return Pid(pId)
}
func kill(pId Pid) error {
pid := int(pId)
// kill process using tskill or taskkill
var killCmd *exec.Cmd
if isCommandAvailable("tskill") {
killCmd = exec.Command("tskill", strconv.Itoa(pid))
} else {
killCmd = exec.Command("taskkill", "/F", "/T", "/PID", strconv.Itoa(pid))
}
stdout, err := killCmd.CombinedOutput()
if err != nil {
fmt.Println("❌ Error killing process:", stdout, ", rc = ", err)
}
return err
}
func startCommand(processCommand string) (Pid, error) {
pid := 0
command := strings.Fields(processCommand)
logInfo("Start command: %s", processCommand)
cmd := exec.Command(command[0], command[1:]...)
err := cmd.Start()
if err == nil {
pid = cmd.Process.Pid
}
return Pid(pid), err
}