From 443386855ca1f4d28d990ae9e46e9bc1533de994 Mon Sep 17 00:00:00 2001 From: build Date: Thu, 20 Jul 2017 20:09:41 -0400 Subject: [PATCH] Fix race condition with unix process listing --- process_unix.go | 56 ++++++++++++++++++++++--------------------------- 1 file changed, 25 insertions(+), 31 deletions(-) diff --git a/process_unix.go b/process_unix.go index 3b733ce..23a61b0 100644 --- a/process_unix.go +++ b/process_unix.go @@ -4,7 +4,6 @@ package ps import ( "fmt" - "io" "os" "strconv" ) @@ -55,41 +54,36 @@ func processes() ([]Process, error) { defer d.Close() results := make([]Process, 0, 50) - for { - fis, err := d.Readdir(10) - if err == io.EOF { - break + fis, err := d.Readdir(-1) + if err != nil { + return nil, err + } + + for _, fi := range fis { + // We only care about directories, since all pids are dirs + if !fi.IsDir() { + continue } + + // We only care if the name starts with a numeric + name := fi.Name() + if name[0] < '0' || name[0] > '9' { + continue + } + + // From this point forward, any errors we just ignore, because + // it might simply be that the process doesn't exist anymore. + pid, err := strconv.ParseInt(name, 10, 0) if err != nil { - return nil, err + continue } - for _, fi := range fis { - // We only care about directories, since all pids are dirs - if !fi.IsDir() { - continue - } - - // We only care if the name starts with a numeric - name := fi.Name() - if name[0] < '0' || name[0] > '9' { - continue - } - - // From this point forward, any errors we just ignore, because - // it might simply be that the process doesn't exist anymore. - pid, err := strconv.ParseInt(name, 10, 0) - if err != nil { - continue - } - - p, err := newUnixProcess(int(pid)) - if err != nil { - continue - } - - results = append(results, p) + p, err := newUnixProcess(int(pid)) + if err != nil { + continue } + + results = append(results, p) } return results, nil