How can I get the list of currently running processes in Go?
The OS package provides some functions: http://golang.org/pkg/os/ but doesn't give anything to see the list of running processes.
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?
If you only need the process information, can just run "ps" command from your go code, then parse the text output.
A complete solution can refer to Exercise 29 in Book "Learning Go" @ http://www.miek.nl/files/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
", infoStat.Procs)
miscStat, _ := load.Misc()
fmt.Printf("Running processes: %d
", miscStat.ProcsRunning)
}
The library allows to get several other data. Take a look at the documentation for avaialable informations provided according to the target operative system.
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
",process.Pid(),process.Executable())
// do os.* stuff on the pid
}
}