List of currently running process in Go

I suggest to use for this purpose the following library: https://github.com/shirou/gopsutil/

Here is an example to get total processes and running ones:

package main

import (
    "fmt"
    "github.com/shirou/gopsutil/host"
    "github.com/shirou/gopsutil/load"
)

func main() {
    infoStat, _ := host.Info()
    fmt.Printf("Total processes: %d\n", infoStat.Procs)

    miscStat, _ := load.Misc()
    fmt.Printf("Running processes: %d\n", miscStat.ProcsRunning)
}

The library allows to get several other data. Take a look at the documentation for available informations provided according to the target operative system.


There is no such function in the standard library and most likely never will be.

In most cases, the list of processes isn't required by programs. Go programs usually want to wait for a single or a smaller number of processes, not for all processes. PIDs of processes are usually obtained by other means than searching the list of all processes.

If you are on Linux, the list of processes can be obtained by reading contents of /proc directory. See question Linux API to list running processes?


This library: github.com/mitchellh/go-ps worked for me.

import (
      ps "github.com/mitchellh/go-ps"
      ... // other imports here...
)

func whatever(){
    processList, err := ps.Processes()
    if err != nil {
        log.Println("ps.Processes() Failed, are you using windows?")
        return
    }

    // map ages
    for x := range processList {
        var process ps.Process
        process = processList[x]
        log.Printf("%d\t%s\n",process.Pid(),process.Executable())

        // do os.* stuff on the pid
    }
}

Tags:

Go