1

This is the command that i execute

$ ps -e
  PID    PPID    PGID     WINPID   TTY         UID    STIME COMMAND
 4372       1    4372       4372  ?         197608 03:44:57 /usr/bin/mintty
 6476    4372    6476       6208  pty0      197608 03:44:58 /usr/bin/bash
14484    6476   14484      12888  pty0      197608 13:23:48 /usr/bin/ps

I get 1d array of strings using bufio scanner.scanLines. I need to convert this into array of structs:

type ProcessInfo struct {
    PID string `json:"PID"`
    PPID string `json:"PPID"`
    PGID string `json:"PGID"`
    WINPID string    `json:"WINPID"`
    TTY   string `json:"TTY"`
    UID string `json:"UID"`
    STIME string `json:"STIME"`
    COMMAND string `json:"COMMAND"`
}

Any help would be appreciated.

2
  • Do you mean "convert this into array of structs"? Because struct you provided can hold only one line of output. Commented Sep 23, 2016 at 20:39
  • @divan Yeah you are right.I meant array of ProcessInfo structs. Commented Sep 23, 2016 at 20:41

1 Answer 1

3

There is a handy strings.Fields function in strings package that helps to parse this kind of output. Go likes pragmatic approaches, so the naive implementation would be:

  • iterate over your array and split each line into fields with whitespace as separator
  • construct new ProcessInfo object from these fields
  • add this object to the array

Assuming your array is named lines, just do something like this:

var pinfos []ProcessInfo
for _, line := range lines {
    fields := strings.Fields(line)

    pi := ProcessInfo{
        PID:     fields[0],
        PPID:    fields[1],
        PGID:    fields[2],
        WINPID:  fields[3],
        TTY:     fields[4],
        UID:     fields[5],
        STIME:   fields[6],
        COMMAND: fields[7],
    }

    pinfos = append(pinfos, pi)
}

See the whole code here: https://play.golang.org/p/wo8FFiYabA

Sign up to request clarification or add additional context in comments.

1 Comment

The following code will suffice for any command we execute like "ps" , "ps -e" or "ps -f" play.golang.org/p/G8tDIoZkf9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.