Strip off version numbers from dir name
[dockapps.git] / wmcpuload / src / cpu_solaris.c
blobe90e656a7cb1b8a157087cb66728c72f3d74cc95
1 /*
2 * cpu_solaric.c - module to get cpu usage, for Solaris
4 * Copyright (C) 2001 Jonathan Lang <lang@synopsys.com>
5 * Copyright (C) 2002 Seiichi SATO <ssato@sh.rim.or.jp>
7 * licensed under the GPL
8 */
10 #ifdef HAVE_CONFIG_H
11 #include "config.h"
12 #endif
14 #include <stdio.h>
15 #include <unistd.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include "cpu.h"
20 #include <kstat.h>
21 #include <sys/cpuvar.h>
22 #include <sys/sysinfo.h>
24 kstat_t **cpu_ks;
25 cpu_stat_t *cpu_stat;
27 void
28 cpu_init(void)
30 /* You don't need initialization under solaris */
31 return;
34 /* returns current CPU usage in percent */
35 int
36 cpu_get_usage(cpu_options *opts)
38 static long oldload, oldtotal;
39 long cpuload, cputotal;
40 int result, ncpus, i;
41 kstat_ctl_t *kc;
42 kstat_named_t *kn;
43 kstat_t *ks;
45 kc = kstat_open();
46 if (!kc) {
47 perror("kstat_open");
48 exit(1);
51 ks = kstat_lookup(kc, "unix", 0, "system_misc");
52 if (kstat_read(kc, ks, NULL) == -1) {
53 perror("kstat_read");
54 exit(1);
58 * Find out how many CPUs the machine has
60 kn = kstat_data_lookup(ks, "ncpus");
61 ncpus = kn->value.ul;
64 * Get CPU usage stats.
66 cpu_ks = (kstat_t **) realloc(cpu_ks, ncpus * sizeof(kstat_t *));
67 cpu_stat =
68 (cpu_stat_t *) realloc(cpu_stat, ncpus * sizeof(cpu_stat_t));
70 for (i = 0, ks = kc->kc_chain; ks; ks = ks->ks_next) {
71 if (strncmp(ks->ks_name, "cpu_stat", 8) == 0)
72 cpu_ks[i++] = ks;
75 for (i = 0; i < ncpus; ++i)
76 (void) kstat_read(kc, cpu_ks[i], &cpu_stat[i]);
79 * Sum the times for the various non-idle CPU_STATES, for Solaris the
80 * CPU_STATES are:
82 * CPU_IDLE 0
83 * CPU_USER 1
84 * CPU_KERNEL 2
85 * CPU_WAIT 3
87 for (cpuload = 0, i = 0; i < ncpus; ++i) {
88 cpuload += (long) cpu_stat[i].cpu_sysinfo.cpu[CPU_USER];
89 cpuload += (long) cpu_stat[i].cpu_sysinfo.cpu[CPU_KERNEL];
90 cpuload += (long) cpu_stat[i].cpu_sysinfo.cpu[CPU_WAIT];
94 * Total Time
96 for (cputotal = cpuload, i = 0; i < ncpus; ++i)
97 cputotal += (long) cpu_stat[i].cpu_sysinfo.cpu[CPU_IDLE];
99 kstat_close(kc);
101 if (oldtotal == 0) {
102 result = 0;
103 } else if ((cputotal - oldtotal) > 0) {
104 result = (100 * (double) (cpuload - oldload)) /
105 (double) (cputotal - oldtotal);
106 } else if (cputotal == oldtotal) {
107 result = 0;
108 } else
109 result = 0;
111 oldload = cpuload;
112 oldtotal = cputotal;
114 return result;