-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathproc.go
More file actions
57 lines (54 loc) · 1.36 KB
/
proc.go
File metadata and controls
57 lines (54 loc) · 1.36 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
package wallutils
import (
"os"
"os/exec"
"strings"
)
// RunningWithArgs checks if the given command is running with the specified args
func RunningWithArgs(command, args string) (bool, error) {
// First try reading /proc directly (Linux)
if found, err := checkProcFSForArgs(command, args); err == nil {
return found, nil
}
// Fallback to pgrep (works on both Linux and FreeBSD)
output, err := exec.Command("pgrep", "-f", command+".*"+args).Output()
if err != nil {
return false, err
}
return len(strings.TrimSpace(string(output))) > 0, nil
}
func checkProcFSForArgs(command, args string) (bool, error) {
entries, err := os.ReadDir("/proc")
if err != nil {
return false, err
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
// Check if directory name is numeric (PID)
pid := entry.Name()
if len(pid) == 0 || pid[0] < '0' || pid[0] > '9' {
continue
}
cmdlineFile := "/proc/" + pid + "/cmdline"
cmdline, err := os.ReadFile(cmdlineFile)
if err != nil {
continue
}
// cmdline uses null bytes as separators
cmdArgs := strings.Split(string(cmdline), "\x00")
if len(cmdArgs) < 2 {
continue
}
// Check if it's the target command with the specified args
if strings.Contains(cmdArgs[0], command) {
for _, arg := range cmdArgs[1:] {
if arg == args {
return true, nil
}
}
}
}
return false, nil
}