gpt4 book ai didi

linux - 在 Golang 中统计 linux 上的进程

转载 作者:IT王子 更新时间:2023-10-29 01:52:47 25 4
gpt4 key购买 nike

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

最佳答案

您可以在此处找到 Linux ps 用于遍历进程列表的代码:

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

简而言之,算法是:

  1. opendir/proc
  2. 调用 readdir 直到返回第一个字符为数字的条目。

因此要计算进程数,您可以通读整个目录并计算有多少条目匹配。

您可以使用 os.Open 在 Go 中执行此操作打开/proc,然后调用Readdirnames方法列出进程。

关于linux - 在 Golang 中统计 linux 上的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34714320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com