英文:
Counting the processes on linux in Golang
问题
我正在开发一个插件,可以统计运行在Linux系统上的进程数量。我已经搜索了一些资料,似乎需要访问/proc目录并从中收集信息。我还尝试使用os、os/exec和syscall包来运行外部命令ps -A --no-headers | wc -l
,但这也没有起作用。我也是用golang编写的。欢迎提供任何帮助或建议。
英文:
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.
答案1
得分: 4
你可以在这里找到Linux ps
使用的代码来遍历进程列表:
https://gitlab.com/procps-ng/procps/blob/master/proc/readproc.c#L1167
简而言之,算法如下:
- 在
/proc
上调用opendir
- 调用
readdir
直到返回一个以数字开头的条目。
因此,要计算进程的数量,你可以遍历整个目录并计算匹配的条目数。
你可以使用Go中的os.Open
打开/proc
,然后调用Readdirnames
方法列出进程。
英文:
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:
opendir
on/proc
- 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.
答案2
得分: 1
以下是翻译好的内容:
以下程序适用于我:
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("运行中的进程数量:%s\n", out)
}
请注意,你必须使用/bin/sh -c
。exec.Command
执行一个单独的程序(可执行文件),比如/bin/sh
、ps
或tail
。
当你在命令提示符中输入ps -A --no-headers | wc -l
时,这个表达式会被一个shell程序(比如/bin/sh
)解释,并且shell程序会启动两个程序(ps
和wc
),并将第一个程序的输出通过管道(|
)传递给第二个程序的输入。
/bin/sh -c command
等同于在终端中输入command
(有一些细微的差别,请阅读man sh
获取更多详细信息)。
英文:
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\n", 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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论