Skip to content

Commit

Permalink
Revert "simplify ps command"
Browse files Browse the repository at this point in the history
This reverts commit 067ce21.

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

"github.com/urfave/cli"
Expand Down Expand Up @@ -41,28 +42,58 @@ 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{"-f"}
psArgs = []string{"-ef"}
}

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

fmt.Printf(string(output))
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
}
}
}
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 1a6391b

Please sign in to comment.