Help me to sort an array of processes

func main() {
r1, w1 := io.Pipe()
var cmds = []*exec.Cmd{
exec.Command(“ls”, “-l”),
exec.Command(“ps”, “-A”),
}
cmds[1].Stdin, cmds[0].Stdout = r1, w1
cmds[1].Stdout = os.Stdout

if err := cmds[0].Start(); err != nil {
	fmt.Println(err)
	return
}
if err := cmds[1].Start(); err != nil {
	fmt.Println(err)
	return
}

cmds[1].Run()
cmds[0].Run()

}

Hi, @siquency, welcome to the forum. What are you trying to sort these processes by?

from a to z and z to a
by PID from 1…N and vice versa
the user must wrote in terminal whicj sort he need
Hope you do this

It is unlikely that anyone on this site will write an entire program that solves your whole problem and give it to you. There are other web sites where you can pay people to do that for you, but the goal of the members on this site is to help guide you so you can solve the problem (mostly) yourself.

That being said,

Is there any reason you’re parsing the text output of ls instead of using built-in functions like (*os.File).Readdirnames or using a library like GitHub - shirou/gopsutil: psutil for golang instead of parsing the output of ps?

1 Like

I need help with how to write the output of these processes into an array and how to sort them

You have 3 problems.

  1. Reading the programs outputs
  2. Splitting a string into a slice of lines
  3. Sorting a slice of strings

Tackle them individually, then put some glue in-between and it should stick together.

1 Like

I don’t know how to do all this, could you help with the first point?

Check out the documentation of the os/exec package, especially the (*exec.Cmd).StdoutPipe example. In that example, the stdout pipe is passed to json.NewDecoder which is not what you need for your situation. You would probably want to take that stdout pipe and pass it to bufio.NewReader which has a convenient ReadString method that should get you started with reading the output of the commands.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.