1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
/*
* cpu_freebsd.c - get cpu usage
*
* Copyright (C) 2003 Alexey Dokuchaev <danfe@regency.nsu.ru>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
*/
#include <osreldate.h>
#if __FreeBSD_version > 500100
#include <sys/time.h>
#include <sys/resource.h>
#else
#include <sys/dkstat.h>
#endif
#include <sys/types.h>
#include <fcntl.h>
#include <kvm.h>
#include <nlist.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static kvm_t *kd;
static int cp_time_mib[2];
static struct nlist nlst[] = {
{"_cp_time"}, {0}};
void
cpu_init(void)
{
size_t len = 2;
sysctlnametomib("kern.cp_time", cp_time_mib, &len);
if((kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open")) != NULL ){
kvm_nlist(kd, nlst);
}
seteuid(getuid());
setegid(getgid());
if (geteuid() != getuid() || getegid() != getgid())
{
perror("sete?id");
exit(1);
}
}
long cpu_used;
long oldused;
long oldtotal;
int history[17];
void cpu_getusage()
{
long cpu, nice, system, idle, used, total;
long cpu_time[CPUSTATES], cpu_time_len=sizeof(cpu_time);
int error;
if( cp_time_mib[0] != 0 ){
error = sysctl(cp_time_mib, 2, cpu_time, &cpu_time_len, NULL, 0 );
if ( error ){
perror("sysctl, cpu_time_mib");
exit(1);
}
}
else {
if (kvm_read(kd, nlst[0].n_value, &cpu_time, sizeof(cpu_time))
!= sizeof(cpu_time))
{
perror("kvm_read");
exit(1);
}
}
cpu = cpu_time[CP_USER];
nice = cpu_time[CP_NICE];
system = cpu_time[CP_SYS];
idle = cpu_time[CP_IDLE];
used = cpu + nice + system;
total = used + idle;
if ((total - oldtotal) != 0)
cpu_used = (100 * (double)(used - oldused)) /
(double)(total - oldtotal);
else
cpu_used = 0;
oldused = used;
oldtotal = total;
memmove(history + 1, history, 16 * sizeof(int));
history[0] = (double)cpu_used * 16 / 100;
}
|