Go中当前正在运行的进程列表

Kun*_*ati 17 go

如何获取Go中当前正在运行的进程列表?

操作系统包提供了一些功能:http://golang.org/pkg/os/ 但是没有任何内容可以查看正在运行的进程列表.

小智 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)


gre*_*lea 7

我建议为此使用以下库: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)

该库允许获取其他几个数据。查看文档以了解根据目标操作系统提供的可用信息。


yon*_*zhy 5

如果您只需要进程信息,可以从您的 go 代码中运行“ps”命令,然后解析文本输出。

完整的解决方案可以参考“Learning Go”一书中的练习29@ http://www.miek.nl/files/go/