github.com/zhuohuang-hust/src-cbuild@v0.0.0-20230105071821-c7aab3e7c840/mergeCode/runc/ps.go (about) 1 // +build linux 2 3 package main 4 5 import ( 6 "encoding/json" 7 "fmt" 8 "os" 9 "os/exec" 10 "strconv" 11 "strings" 12 13 "github.com/urfave/cli" 14 ) 15 16 var psCommand = cli.Command{ 17 Name: "ps", 18 Usage: "ps displays the processes running inside a container", 19 ArgsUsage: `<container-id> [ps options]`, 20 Flags: []cli.Flag{ 21 cli.StringFlag{ 22 Name: "format, f", 23 Value: "", 24 Usage: `select one of: ` + formatOptions, 25 }, 26 }, 27 Action: func(context *cli.Context) error { 28 container, err := getContainer(context) 29 if err != nil { 30 return err 31 } 32 33 pids, err := container.Processes() 34 if err != nil { 35 return err 36 } 37 38 if context.String("format") == "json" { 39 if err := json.NewEncoder(os.Stdout).Encode(pids); err != nil { 40 return err 41 } 42 return nil 43 } 44 45 // [1:] is to remove command name, ex: 46 // context.Args(): [containet_id ps_arg1 ps_arg2 ...] 47 // psArgs: [ps_arg1 ps_arg2 ...] 48 // 49 psArgs := context.Args()[1:] 50 if len(psArgs) == 0 { 51 psArgs = []string{"-ef"} 52 } 53 54 cmd := exec.Command("ps", psArgs...) 55 output, err := cmd.CombinedOutput() 56 if err != nil { 57 return fmt.Errorf("%s: %s", err, output) 58 } 59 60 lines := strings.Split(string(output), "\n") 61 pidIndex, err := getPidIndex(lines[0]) 62 if err != nil { 63 return err 64 } 65 66 fmt.Println(lines[0]) 67 for _, line := range lines[1:] { 68 if len(line) == 0 { 69 continue 70 } 71 fields := strings.Fields(line) 72 p, err := strconv.Atoi(fields[pidIndex]) 73 if err != nil { 74 return fmt.Errorf("unexpected pid '%s': %s", fields[pidIndex], err) 75 } 76 77 for _, pid := range pids { 78 if pid == p { 79 fmt.Println(line) 80 break 81 } 82 } 83 } 84 return nil 85 }, 86 SkipArgReorder: true, 87 } 88 89 func getPidIndex(title string) (int, error) { 90 titles := strings.Fields(title) 91 92 pidIndex := -1 93 for i, name := range titles { 94 if name == "PID" { 95 return i, nil 96 } 97 } 98 99 return pidIndex, fmt.Errorf("couldn't find PID field in ps output") 100 }