duangao8359
2016-01-11 04:45
浏览 141

在Golang中计算Linux上的进程

I am working on a plugin that can count the processes running on a Linux system. I have searched around and it seems that I need to access /proc and gather information from there. I also tried using the os, os/exec, and syscall packages to run the external command ps -A --no-headers | wc -l but this isn't working either. I am coding this in golang as well. Any help or suggestions are welcome.

图片转代码服务由CSDN问答提供 功能建议

我正在开发一个插件,该插件可以计算Linux系统上运行的进程。 我到处搜索,似乎我需要访问/ proc并从那里收集信息。 我还尝试使用os,os / exec和syscall软件包来运行外部命令 ps -A --no-headers | wc -l <​​/ code>,但这也不起作用。 我也在golang中编码。 欢迎任何帮助或建议。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongtan7639 2016-01-11 06:19
    已采纳

    You can find the code that the Linux ps uses to iterate through the list of processes here:

    https://gitlab.com/procps-ng/procps/blob/master/proc/readproc.c#L1167

    In short, the algorithm is:

    1. opendir on /proc
    2. call readdir until an entry whose first character is a digit is returned.

    So to count the number of processes, you can read through the entire directory and count how many entries match.

    You can do this in Go using os.Open to open /proc, and then call the Readdirnames method to list the processes.

    点赞 打赏 评论
  • dsgk0386 2016-01-11 06:07

    The following program works for me:

    package main
    
    import (
        "fmt"
        "log"
        "os/exec"
    )
    
    func main() {
        out, err := exec.Command("/bin/sh", "-c", "ps -A --no-headers | wc -l").Output()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("Number of running processes: %s
    ", out)
    }
    

    Note that you have to use /bin/sh -c. exec.Command executes a single program (an executable file), such as /bin/sh or ps or tail.

    When you type ps -A --no-headers | wc -l in your command prompt this expression is interpreted by a shell program (such as /bin/sh) and the shell program launches two programs (ps and wc) and pipes (|) the output of the first program to the input of the second program.

    /bin/sh -c command is equivalent to typing command in a terminal (with some minor differences, read man sh for more details).

    点赞 打赏 评论

相关推荐 更多相似问题