Skip to content

Commit 2ad2cf7

Browse files
Merge pull request #1092 from datawolf/simplify-ps-command
simplify ps command
2 parents d1fc802 + 067ce21 commit 2ad2cf7

File tree

1 file changed

+8
-39
lines changed

1 file changed

+8
-39
lines changed

ps.go

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

1312
"github.com/urfave/cli"
@@ -42,58 +41,28 @@ var psCommand = cli.Command{
4241
return nil
4342
}
4443

44+
pidlist := []string{}
45+
for _, pid := range pids {
46+
pidlist = append(pidlist, fmt.Sprintf("%d", pid))
47+
}
48+
4549
// [1:] is to remove command name, ex:
4650
// context.Args(): [containet_id ps_arg1 ps_arg2 ...]
4751
// psArgs: [ps_arg1 ps_arg2 ...]
4852
//
4953
psArgs := context.Args()[1:]
5054
if len(psArgs) == 0 {
51-
psArgs = []string{"-ef"}
55+
psArgs = []string{"-f"}
5256
}
5357

58+
psArgs = append(psArgs, "-p", strings.Join(pidlist, ","))
5459
output, err := exec.Command("ps", psArgs...).Output()
5560
if err != nil {
5661
return err
5762
}
5863

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-
}
64+
fmt.Printf(string(output))
8365
return nil
8466
},
8567
SkipArgReorder: true,
8668
}
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)