在FreeBSD上的C中,如何访问cpu利用率?
我正在编写一些代码来处理HTTP重定向.如果cpu负载超过FReeBSD系统的阈值,我想重定向客户端请求.查看手册页,kvm_getpcpu()似乎是正确的答案,但手册页(我读过)没有记录用法.
任何提示或指示都会受到欢迎 – 谢谢!
在这里阅读答案后,我能够提出以下内容.由于文档很差,我不是100%肯定它是正确的,但顶部似乎同意.感谢所有回答的人.
- #include <stdio.h>
- #include <string.h>
- #include <sys/types.h>
- #include <sys/sysctl.h>
- #include <unistd.h>
- #define CP_USER 0
- #define CP_NICE 1
- #define CP_SYS 2
- #define CP_INTR 3
- #define CP_IDLE 4
- #define cpuSTATES 5
- int main()
- {
- long cur[cpuSTATES],last[cpuSTATES];
- size_t cur_sz = sizeof cur;
- int state,i;
- long sum;
- double util;
- memset(last,sizeof last);
- for (i=0; i<6; i++)
- {
- if (sysctlbyname("kern.cp_time",&cur,&cur_sz,NULL,0) < 0)
- {
- printf ("Error reading kern.cp_times sysctl\n");
- return -1;
- }
- sum = 0;
- for (state = 0; state<cpuSTATES; state++)
- {
- long tmp = cur[state];
- cur[state] -= last[state];
- last[state] = tmp;
- sum += cur[state];
- }
- util = 100.0L - (100.0L * cur[CP_IDLE] / (sum ? (double) sum : 1.0L));
- printf("cpu utilization: %7.3f\n",util);
- sleep(1);
- }
- return 0;
- }
解决方法
从MAN页面
kvm_getmaxcpu,kvm_getpcpu – 访问每cpu数据
图书馆
内核数据访问库(libkvm,-lkvm)
概要
描述
kvm_getmaxcpu()和kvm_getpcpu()函数用于访问
由kd指示的内核中活动处理器的每cpu数据.该
kvm_getmaxcpu()函数返回支持的最大cpu数
内核. kvm_getpcpu()函数返回一个缓冲区,其中包含
单个cpu的cpu数据.这个缓冲区由struct pcpu描述
类型.调用者负责通过调用释放缓冲区
免费(3)不再需要时.如果cpu不活动,则为NULL
而是返回.
CACHING
这些函数缓存各种内核变量的nlist值
在连续的调用中重复使用.您可以使用kd set调用任一函数
为NULL以清除此缓存.
返回值
成功时,kvm_getmaxcpu()函数返回最大数量
内核支持的cpu.如果发生错误,则返回-1.
成功时,kvm_getpcpu()函数返回指向已分配的指针
缓冲区或NULL.如果发生错误,则返回-1.
如果任一函数遇到错误,则可能出现错误消息
通过kvm_geterr检索(3.)
编辑
这是kvm_t结构:
- struct __kvm {
- /*
- * a string to be prepended to error messages
- * provided for compatibility with sun's interface
- * if this value is null,errors are saved in errbuf[]
- */
- const char *program;
- char *errp; /* XXX this can probably go away */
- char errbuf[_POSIX2_LINE_MAX];
- #define ISALIVE(kd) ((kd)->vmfd >= 0)
- int pmfd; /* physical memory file (or crashdump) */
- int vmfd; /* virtual memory file (-1 if crashdump) */
- int unused; /* was: swap file (e.g.,/dev/drum) */
- int nlfd; /* namelist file (e.g.,/kernel) */
- struct kinfo_proc *procbase;
- char *argspc; /* (dynamic) storage for argv strings */
- int arglen; /* length of the above */
- char **argv; /* (dynamic) storage for argv pointers */
- int argc; /* length of above (not actual # present) */
- char *argbuf; /* (dynamic) temporary storage */
- /*
- * Kernel virtual address translation state. This only gets filled
- * in for dead kernels; otherwise,the running kernel (i.e. kmem)
- * will do the translations for us. It could be big,so we
- * only allocate it if necessary.
- */
- struct vmstate *vmst;
- };