Add ps command

Signed-off-by: Qiang Huang <h.huangqiang@huawei.com>
This commit is contained in:
Qiang Huang 2016-04-22 08:06:35 +08:00
parent d14b04a331
commit 8cf9ca4bcf
2 changed files with 77 additions and 0 deletions

View File

@ -93,6 +93,7 @@ func main() {
killCommand, killCommand,
listCommand, listCommand,
pauseCommand, pauseCommand,
psCommand,
restoreCommand, restoreCommand,
resumeCommand, resumeCommand,
specCommand, specCommand,

76
ps.go Normal file
View File

@ -0,0 +1,76 @@
// +build linux
package main
import (
"fmt"
"os/exec"
"strconv"
"strings"
"github.com/codegangsta/cli"
)
var psCommand = cli.Command{
Name: "ps",
Usage: "ps displays the processes running inside a container",
ArgsUsage: `<container-id> <ps options>`,
Action: func(context *cli.Context) {
container, err := getContainer(context)
if err != nil {
fatal(err)
}
psArgs := context.Args().Get(1)
if psArgs == "" {
psArgs = "-ef"
}
output, err := exec.Command("ps", strings.Split(psArgs, " ")...).Output()
if err != nil {
fatal(err)
}
lines := strings.Split(string(output), "\n")
pidIndex, err := getPidIndex(lines[0])
if err != nil {
fatal(err)
}
pids, err := container.Processes()
if err != nil {
fatal(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 {
fatal(fmt.Errorf("unexpected pid '%s': %s", fields[pidIndex], err))
}
for _, pid := range pids {
if pid == p {
fmt.Println(line)
break
}
}
}
},
}
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")
}