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 --- main/main.go | 1 + process/process.go | 26 ++++++++++++++++++-------- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/main/main.go b/main/main.go index 72497df..e408e4b 100644 --- a/main/main.go +++ b/main/main.go @@ -38,6 +38,7 @@ func main() { for counter := 0; counter < 3; counter++ { timer <- true time.Sleep(time.Second) + fmt.Printf("Next... %d\n", counter) } timer <- false 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