Linux中获取CPU负载的C API

14

在Linux上,有没有内置的C库函数可以获取机器的CPU负载? 我可以编写自己的函数来打开和解析/proc目录下的文件,但似乎应该有更好的方法。

  • 不需要可移植性
  • 不能需要除基本RHEL4安装之外的任何库。

1
访问/proc是Unix的做事方式。一切皆文件。我猜你是微软程序员?他们似乎总是对这个概念感到不舒服。 - Stu Thompson
1
访问/proc是Linux的方法。并不是每个Unix都具备这个功能(尽管它很好)。 - dmckee --- ex-moderator kitten
@dmckee:RHEL4可以,而这是@jcs的要求。 - Stu Thompson
5个回答

13
如果您真的需要一个C接口,请使用getloadavg(),它也适用于没有/proc的Unix系统。
它有一个包含所有细节的手册页面

1
事实上,尽管所有关于“Unix方法”的膨胀都不属实,但这确实是一种可移植的方式。当然,在Linux上,它只是在/proc读取之上的库函数。 - Andy Ross
负载平均值 不是 CPU 负载的表示。所谓 CPU 负载,指的是你餐厅里有多少服务员正在忙碌。负载平均值告诉你外面等待入座的客人数量 + 正在用餐的客人数量。这两者并不是_同一件事。我认为在这里使用 /proc/stat 更加相关。 - m-ric

9

获取Linux CPU负载信息的首选方法是从/proc/stat/proc/loadavg/proc/uptime中读取。所有常规的Linux实用工具,如top,都使用这种方法。


2

来自 proc (5) 手册:

   /proc/loadavg
          The  first  three  fields  in this file are load average figures
          giving the number of jobs in the run queue (state R) or  waiting
          for disk I/O (state D) averaged over 1, 5, and 15 minutes.  They
          are the same as the load average numbers given by uptime(1)  and
          other  programs.  The fourth field consists of two numbers sepaâ
          rated by a slash (/).  The first of these is the number of  curâ
          rently   executing   kernel   scheduling   entities  (processes,
          threads); this will be less than or equal to the number of CPUs.
          The  value  after  the  slash is the number of kernel scheduling
          entities that currently exist on the system.  The fifth field is
          the  PID  of  the  process that was most recently created on the
          system.

1

我的理解是,解析/proc的内容是官方提供的接口之一(那里有许多文件在呈现给用户之前应该先被解析)。


1
“负载平均值”可能并不是非常有用。我们发现它的用处有限,因为它实际上并没有告诉你有多少CPU正在使用,只有“准备运行”的任务的平均数量。“准备运行”有点主观,但并不是很有帮助,因为它经常包括等待IO的进程。
在繁忙的系统中,我们看到8个核心的机器上的负载平均值超过20,而CPU仍然相对空闲。
如果您想查看正在使用的CPU,请查看/proc中的各种文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接