From f6473fc7afd385b652e1ccdb745c43292f14a852 Mon Sep 17 00:00:00 2001 From: "Paul Buetow (europa)" Date: Sun, 24 May 2015 23:51:00 +0100 Subject: Add error handling --- process/process.go | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) (limited to 'process') diff --git a/process/process.go b/process/process.go index 6f4ec11..7436d16 100644 --- a/process/process.go +++ b/process/process.go @@ -1,6 +1,7 @@ package process import ( + "errors" "fmt" "io/ioutil" "log" @@ -13,6 +14,19 @@ type Process struct { Cmdline string } +func new(pidstr string) (Process, error) { + pid, _ := strconv.Atoi(pidstr) + bytes, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)) + if err != nil { + log.Fatal(err) + } + if len(bytes) > 0 { + return Process{Pid: pid, Cmdline: string(bytes)}, nil + } else { + return Process{}, errors.New("Can not read process information") + } +} + func (self *Process) String() string { str := "=========================" @@ -22,7 +36,7 @@ func (self *Process) String() string { return str } -func Gather(res chan<- Process) { +func Gather(processes chan<- Process) { re, _ := regexp.Compile("^[0-9]+$") dir, err := ioutil.ReadDir("/proc/") @@ -33,13 +47,9 @@ func Gather(res chan<- Process) { for _, direntry := range dir { name := direntry.Name() if re.MatchString(name) { - pid, _ := strconv.Atoi(name) - bytes, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)) - if err != nil { - log.Fatal(err) - } - if len(bytes) > 0 { - res <- Process{Pid: pid, Cmdline: string(bytes)} + process, err := new(name) + if err == nil { + processes <- process } } } -- cgit v1.2.3