Strip off version numbers from dir name
[dockapps.git] / wmcpuload / src / cpu_freebsd.c
blob9d7bc7ca5dd843a107c00762b82a1657a6897932
1 /*
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
7 */
9 #ifdef HAVE_CONFIG_H
10 #include "config.h"
11 #endif
13 #include <stdio.h>
14 #include <unistd.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include "cpu.h"
19 #include <kvm.h>
20 #include <fcntl.h>
21 #include <sys/dkstat.h>
23 static kvm_t *kd = NULL;
24 static struct nlist nlst[] = { {"_cp_time"}, {0} };
26 void
27 cpu_init(void)
30 kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open");
32 if (kd == NULL) {
33 fprintf(stderr, "can't open kernel virtual memory");
34 exit(1);
37 kvm_nlist(kd, nlst);
39 if (nlst[0].n_type == 0) {
40 fprintf(stderr, "error extracting symbols");
41 exit(1);
44 /* drop setgid & setuid (the latter should not be there really) */
45 seteuid(getuid());
46 setegid(getgid());
48 if (geteuid() != getuid() || getegid() != getgid()) {
49 fprintf(stderr, "unable to drop privileges");
50 exit(1);
54 /* returns current CPU usage in percent */
55 int
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)) !=
63 sizeof(cpu_time))
64 return 0;
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];
71 if (pre_total == 0) {
72 result = 0;
73 } else if ((total - pre_total) > 0) {
74 result = (100 * (double) (used - pre_used)) / (double) (total -
75 pre_total);
76 } else {
77 result = 0;
80 pre_used = used;
81 pre_total = total;
83 return result;