wmpop3lb: Use wmgeneral from libdockapp.
[dockapps.git] / wmcpuload / src / cpu_freebsd.c
blobd9308595dee73c7722106039ad49aad5ff3feb6d
1 /*
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
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>
22 #include <sys/param.h>
24 #if __FreeBSD_version < 500101
25 # include <sys/dkstat.h>
26 #else
27 # include <sys/resource.h>
28 #endif /* __FreeBSD_version < 500101 */
30 static kvm_t *kd = NULL;
31 static struct nlist nlst[] = { {"_cp_time"}, {0} };
33 void
34 cpu_init(void)
37 kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open");
39 if (kd == NULL) {
40 fprintf(stderr, "can't open kernel virtual memory");
41 exit(1);
44 kvm_nlist(kd, nlst);
46 if (nlst[0].n_type == 0) {
47 fprintf(stderr, "error extracting symbols");
48 exit(1);
51 /* drop setgid & setuid (the latter should not be there really) */
52 seteuid(getuid());
53 setegid(getgid());
55 if (geteuid() != getuid() || getegid() != getgid()) {
56 fprintf(stderr, "unable to drop privileges");
57 exit(1);
61 /* returns current CPU usage in percent */
62 int
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)) !=
70 sizeof(cpu_time))
71 return 0;
73 /* calculate usage */
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)) {
79 result = 0;
80 } else {
81 result = 100 * (double)(used - pre_used) / (double)(total - pre_total);
84 /* save used/total for next calculation */
85 pre_used = used;
86 pre_total = total;
88 return result;