2 * cpu_freebsd.c - module to get cpu usage, for FreeBSD
4 * Copyright (c) 2001, 2002, 2004 Seiichi SATO <ssato@sh.rim.or.jp>
6 * Licensed under the GPL
22 #include <sys/param.h>
24 #if __FreeBSD_version < 500101
25 # include <sys/dkstat.h>
27 # include <sys/resource.h>
28 #endif /* __FreeBSD_version < 500101 */
30 static kvm_t
*kd
= NULL
;
31 static struct nlist nlst
[] = { {"_cp_time"}, {0} };
37 kd
= kvm_open(NULL
, NULL
, NULL
, O_RDONLY
, "kvm_open");
40 fprintf(stderr
, "can't open kernel virtual memory");
46 if (nlst
[0].n_type
== 0) {
47 fprintf(stderr
, "error extracting symbols");
51 /* drop setgid & setuid (the latter should not be there really) */
55 if (geteuid() != getuid() || getegid() != getgid()) {
56 fprintf(stderr
, "unable to drop privileges");
61 /* returns current CPU usage in percent */
63 cpu_get_usage(cpu_options
*opts
)
65 static int pre_used
, pre_total
;
66 int used
, total
, result
;
67 unsigned long int cpu_time
[CPUSTATES
];
69 if (kvm_read(kd
, nlst
[0].n_value
, &cpu_time
, sizeof(cpu_time
)) !=
74 total
= cpu_time
[CP_USER
] + cpu_time
[CP_SYS
] + cpu_time
[CP_INTR
] +
75 cpu_time
[CP_NICE
] + cpu_time
[CP_IDLE
];
76 used
= cpu_time
[CP_USER
] + cpu_time
[CP_SYS
] + cpu_time
[CP_INTR
] +
77 (opts
->ignore_nice
? 0 : cpu_time
[CP_NICE
]);
78 if ((pre_total
== 0) || !(total
- pre_total
> 0)) {
81 result
= 100 * (double)(used
- pre_used
) / (double)(total
- pre_total
);
84 /* save used/total for next calculation */