|
7 | 7 | "fmt" |
8 | 8 | "os" |
9 | 9 | "os/exec" |
| 10 | + "strconv" |
10 | 11 | "strings" |
11 | 12 |
|
12 | 13 | "github.com/urfave/cli" |
@@ -41,28 +42,58 @@ var psCommand = cli.Command{ |
41 | 42 | return nil |
42 | 43 | } |
43 | 44 |
|
44 | | - pidlist := []string{} |
45 | | - for _, pid := range pids { |
46 | | - pidlist = append(pidlist, fmt.Sprintf("%d", pid)) |
47 | | - } |
48 | | - |
49 | 45 | // [1:] is to remove command name, ex: |
50 | 46 | // context.Args(): [containet_id ps_arg1 ps_arg2 ...] |
51 | 47 | // psArgs: [ps_arg1 ps_arg2 ...] |
52 | 48 | // |
53 | 49 | psArgs := context.Args()[1:] |
54 | 50 | if len(psArgs) == 0 { |
55 | | - psArgs = []string{"-f"} |
| 51 | + psArgs = []string{"-ef"} |
56 | 52 | } |
57 | 53 |
|
58 | | - psArgs = append(psArgs, "-p", strings.Join(pidlist, ",")) |
59 | 54 | output, err := exec.Command("ps", psArgs...).Output() |
60 | 55 | if err != nil { |
61 | 56 | return err |
62 | 57 | } |
63 | 58 |
|
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 | + } |
65 | 83 | return nil |
66 | 84 | }, |
67 | 85 | SkipArgReorder: true, |
68 | 86 | } |
| 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