proc: fix could not read process comm name error

fix #531
This commit is contained in:
guo
2016-05-16 20:22:40 +08:00
parent 218c2b953b
commit c3ade94b86

View File

@ -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)
}