2 * cpu_freebsd.c - module to get cpu usage, for FreeBSD
4 * Copyright (c) 2001, 2002 Seiichi SATO <ssato@sh.rim.or.jp>
6 * Licensed under the GPL
21 #include <sys/dkstat.h>
23 static kvm_t
*kd
= NULL
;
24 static struct nlist nlst
[] = { {"_cp_time"}, {0} };
30 kd
= kvm_open(NULL
, NULL
, NULL
, O_RDONLY
, "kvm_open");
33 fprintf(stderr
, "can't open kernel virtual memory");
39 if (nlst
[0].n_type
== 0) {
40 fprintf(stderr
, "error extracting symbols");
44 /* drop setgid & setuid (the latter should not be there really) */
48 if (geteuid() != getuid() || getegid() != getgid()) {
49 fprintf(stderr
, "unable to drop privileges");
54 /* returns current CPU usage in percent */
56 cpu_get_usage(cpu_options
*opts
)
58 static int pre_used
, pre_total
;
59 int used
, total
, result
;
60 unsigned long int cpu_time
[CPUSTATES
];
62 if (kvm_read(kd
, nlst
[0].n_value
, &cpu_time
, sizeof(cpu_time
)) !=
66 used
= cpu_time
[CP_USER
] + cpu_time
[CP_SYS
];
67 if (!opts
->ignore_nice
)
68 used
+= cpu_time
[CP_NICE
];
69 total
= used
+ cpu_time
[CP_IDLE
];
73 } else if ((total
- pre_total
) > 0) {
74 result
= (100 * (double) (used
- pre_used
)) / (double) (total
-