Skip to content

Commit

Permalink
simplify ps command
Browse files Browse the repository at this point in the history
the `-p pidlist` flag of `ps` command selects the process whose process
ID numbers apper in `pidlist`.[1]

This patch use `-p pidlist` to filter process which we want.

[1]: http://man7.org/linux/man-pages/man1/ps.1.html

Signed-off-by: Wang Long <long.wanglong@huawei.com>
  • Loading branch information
datawolf committed Sep 30, 2016
1 parent 3597b7b commit 067ce21
Showing 1 changed file with 8 additions and 39 deletions.
47 changes: 8 additions & 39 deletions ps.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"fmt"
"os"
"os/exec"
"strconv"
"strings"

"github.com/urfave/cli"
Expand Down Expand Up @@ -42,58 +41,28 @@ var psCommand = cli.Command{
return nil
}

pidlist := []string{}
for _, pid := range pids {
pidlist = append(pidlist, fmt.Sprintf("%d", pid))
}

// [1:] is to remove command name, ex:
// context.Args(): [containet_id ps_arg1 ps_arg2 ...]
// psArgs: [ps_arg1 ps_arg2 ...]
//
psArgs := context.Args()[1:]
if len(psArgs) == 0 {
psArgs = []string{"-ef"}
psArgs = []string{"-f"}
}

psArgs = append(psArgs, "-p", strings.Join(pidlist, ","))
output, err := exec.Command("ps", psArgs...).Output()
if err != nil {
return err
}

lines := strings.Split(string(output), "\n")
pidIndex, err := getPidIndex(lines[0])
if err != nil {
return err
}

fmt.Println(lines[0])
for _, line := range lines[1:] {
if len(line) == 0 {
continue
}
fields := strings.Fields(line)
p, err := strconv.Atoi(fields[pidIndex])
if err != nil {
return fmt.Errorf("unexpected pid '%s': %s", fields[pidIndex], err)
}

for _, pid := range pids {
if pid == p {
fmt.Println(line)
break
}
}
}
fmt.Printf(string(output))
return nil
},
SkipArgReorder: true,
}

func getPidIndex(title string) (int, error) {
titles := strings.Fields(title)

pidIndex := -1
for i, name := range titles {
if name == "PID" {
return i, nil
}
}

return pidIndex, fmt.Errorf("couldn't find PID field in ps output")
}

0 comments on commit 067ce21

Please sign in to comment.