package main import ( "flag" "fmt" "jsh" "os" "os/exec" "strings" ) // Converts raw output of "ps" into a slice of Process objects func PsOutputToProcesses(out string) *[]jsh.Process { processes := []jsh.Process{} lines := strings.Split(out, "\n") header, procs := lines[0], lines[1:] numFields := len(strings.Fields(header)) for _, proc := range procs { p, err := jsh.NewProcess(jsh.FieldsN(proc, numFields)) if err == nil { processes = append(processes, *p) } } return &processes } // Falls back to procps-ng passing the space-separated arguments in the given // args slice. If args is nil, we default to the arguments passed to the command // line using os.Args func fallbackCompletelyWithArgs(args []string) *[]byte { if args == nil { args = os.Args[1:] } out, err := exec.Command("/usr/bin/ps", args...).Output() if err != nil { panic(err) } return &out } // Falls back to procps-ng with no default arguments func fallbackCompletely() *[]byte { return fallbackCompletelyWithArgs(nil) } func runJsonMode() { // Run procps-ng "ps" with full output psOut := string(*fallbackCompletelyWithArgs([]string{"auxww"})) processesPtr := PsOutputToProcesses(psOut) finalOut := jsh.JshOutput{*processesPtr, []string{}} fmt.Printf("%s", *finalOut.ToJson()) } func main() { // Parse for JSON flag. jsonModePtr := flag.Bool("json", false, "a bool") flag.Parse() if !*jsonModePtr { fmt.Printf("%s", fallbackCompletely()) } else { runJsonMode() } }