Merge pull request #1102 from datawolf/Revert-simplify-ps-command

Revert "simplify ps command"
This commit is contained in:
Qiang Huang 2016-10-11 03:53:28 +02:00 committed by GitHub
commit 26ebd6ab63
1 changed files with 39 additions and 8 deletions

47
ps.go
View File

@ -7,6 +7,7 @@ import (
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"github.com/urfave/cli"
@ -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")
}