From c3ade94b86bf9033403a493977047df8dbe5ccdd Mon Sep 17 00:00:00 2001 From: guo Date: Mon, 16 May 2016 20:22:40 +0800 Subject: [PATCH] proc: fix could not read process comm name error fix #531 --- proc/proc_linux.go | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/proc/proc_linux.go b/proc/proc_linux.go index 3ac4d68b..9ead16e2 100644 --- a/proc/proc_linux.go +++ b/proc/proc_linux.go @@ -1,6 +1,7 @@ package proc import ( + "bytes" "debug/gosym" "errors" "fmt" @@ -8,6 +9,7 @@ import ( "os" "os/exec" "path/filepath" + "regexp" "strconv" "strings" "sync" @@ -350,12 +352,30 @@ func (dbp *Process) loadProcessInformation(wg *sync.WaitGroup) { defer wg.Done() comm, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/comm", dbp.Pid)) - if err != nil { - fmt.Printf("Could not read process comm name: %v\n", err) - os.Exit(1) + if err == nil { + // removes newline character + comm = bytes.TrimSuffix(comm, []byte("\n")) + } + + if comm == nil || len(comm) <= 0 { + stat, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/stat", dbp.Pid)) + if err != nil { + fmt.Printf("Could not read proc stat: %v\n", err) + os.Exit(1) + } + expr := fmt.Sprintf("%d\\s*\\((.*)\\)", dbp.Pid) + rexp, err := regexp.Compile(expr) + if err != nil { + fmt.Printf("Regexp compile error: %v\n", err) + os.Exit(1) + } + match := rexp.FindSubmatch(stat) + if match == nil { + fmt.Printf("No match found using regexp '%s' in /proc/%d/stat\n", expr, dbp.Pid) + os.Exit(1) + } + comm = match[1] } - // removes newline character - comm = comm[:len(comm)-1] dbp.os.comm = strings.Replace(string(comm), "%", "%%", -1) }