-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocess.go
72 lines (62 loc) · 1.23 KB
/
process.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
package main
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
)
type Process struct {
Pid int
Executable string
CommandLine string
Tty string
}
func GetProcesses() ([]Process, error) {
cmd := exec.Command("ps", "-eo", "pid,comm,args,tty")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
return nil, err
}
processes := []Process{}
lines := strings.Split(out.String(), "\n")
for _, line := range lines[1:] {
fields := strings.Fields(line)
if len(fields) >= 4 {
pid, err := strconv.Atoi(fields[0])
if err == nil {
process := Process{
Pid: pid,
Executable: fields[1],
CommandLine: fields[2],
Tty: fields[3],
}
processes = append(processes, process)
}
}
}
return processes, nil
}
func FindProcessByPid(pid int) (*Process, error) {
processes, err := GetProcesses()
if err != nil {
return nil, err
}
for _, process := range processes {
if process.Pid == pid {
return &process, nil
}
}
return nil, errors.New(fmt.Sprintf("Process with ID %d not found", pid))
}
func (p *Process) Kill() error {
process, err := os.FindProcess(p.Pid)
if err != nil {
return err
}
return process.Kill()
}