Skip to content

Commit 2451d24

Browse files
committed
fix: correctly exit if process does not exist
1 parent 64c90fa commit 2451d24

1 file changed

Lines changed: 15 additions & 2 deletions

File tree

main.go

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ func main() {
3434
os.Exit(1)
3535
}
3636

37+
if !processExists(pid) {
38+
fmt.Println("Process does not exist")
39+
os.Exit(1)
40+
}
41+
3742
if *flagMonitor {
3843
if *flagTime > 0 {
3944
time.AfterFunc(time.Duration(*flagTime)*time.Second, func() {
@@ -64,9 +69,17 @@ type processOutput struct {
6469
Swap float64
6570
}
6671

72+
// processExists checks if a process exists.
73+
// We are not using os.FindProcess, because it will return a process even if it does not exist
6774
func processExists(pid int) bool {
68-
_, err := os.FindProcess(pid)
69-
return err == nil
75+
cmd := exec.Command("ps", "-p", strconv.Itoa(pid))
76+
cmd.Stderr = os.Stderr
77+
out, err := cmd.Output()
78+
if err != nil {
79+
return false
80+
}
81+
82+
return len(strings.Split(string(out), "\n")) > 2
7083
}
7184

7285
func printVmrss(mainPid int, processes []processOutput, children bool) {

0 commit comments

Comments
 (0)