小智 19
标准库中没有这样的功能,很可能永远不会.
在大多数情况下,程序不需要进程列表.Go程序通常希望等待单个或更少数量的进程,而不是所有进程.过程的PID通常通过除搜索所有过程列表之外的其他方式获得.
如果您使用的是Linux,则可以通过读取目录内容来获取进程列表/proc.请参阅问题Linux API列出正在运行的进程?
Fel*_*des 10
这个库:github.com/mitchellh/go-ps 为我工作。
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
}
}
Run Code Online (Sandbox Code Playgroud)
我建议为此使用以下库:https : //github.com/shirou/gopsutil/
以下是获取总进程数和正在运行的进程数的示例:
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)
}
Run Code Online (Sandbox Code Playgroud)
该库允许获取其他几个数据。查看文档以了解根据目标操作系统提供的可用信息。
如果您只需要进程信息,可以从您的 go 代码中运行“ps”命令,然后解析文本输出。
完整的解决方案可以参考“Learning Go”一书中的练习29@ http://www.miek.nl/files/go/