Skip to content

Commit 26ebd6a

Browse files
authored
Merge pull request #1102 from datawolf/Revert-simplify-ps-command
Revert "simplify ps command"
2 parents 45c30e7 + 1a6391b commit 26ebd6a

File tree

1 file changed

+39
-8
lines changed

1 file changed

+39
-8
lines changed

ps.go

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"fmt"
88
"os"
99
"os/exec"
10+
"strconv"
1011
"strings"
1112

1213
"github.com/urfave/cli"
@@ -41,28 +42,58 @@ var psCommand = cli.Command{
4142
return nil
4243
}
4344

44-
pidlist := []string{}
45-
for _, pid := range pids {
46-
pidlist = append(pidlist, fmt.Sprintf("%d", pid))
47-
}
48-
4945
// [1:] is to remove command name, ex:
5046
// context.Args(): [containet_id ps_arg1 ps_arg2 ...]
5147
// psArgs: [ps_arg1 ps_arg2 ...]
5248
//
5349
psArgs := context.Args()[1:]
5450
if len(psArgs) == 0 {
55-
psArgs = []string{"-f"}
51+
psArgs = []string{"-ef"}
5652
}
5753

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

64-
fmt.Printf(string(output))
59+
lines := strings.Split(string(output), "\n")
60+
pidIndex, err := getPidIndex(lines[0])
61+
if err != nil {
62+
return err
63+
}
64+
65+
fmt.Println(lines[0])
66+
for _, line := range lines[1:] {
67+
if len(line) == 0 {
68+
continue
69+
}
70+
fields := strings.Fields(line)
71+
p, err := strconv.Atoi(fields[pidIndex])
72+
if err != nil {
73+
return fmt.Errorf("unexpected pid '%s': %s", fields[pidIndex], err)
74+
}
75+
76+
for _, pid := range pids {
77+
if pid == p {
78+
fmt.Println(line)
79+
break
80+
}
81+
}
82+
}
6583
return nil
6684
},
6785
SkipArgReorder: true,
6886
}
87+
88+
func getPidIndex(title string) (int, error) {
89+
titles := strings.Fields(title)
90+
91+
pidIndex := -1
92+
for i, name := range titles {
93+
if name == "PID" {
94+
return i, nil
95+
}
96+
}
97+
98+
return pidIndex, fmt.Errorf("couldn't find PID field in ps output")
99+
}

0 commit comments

Comments
 (0)