Listing 1 Sample implementation for the uptime utility
(C)
1 #include <stdio.h>
2 #include <kstat.h>
3 #include <unistd.h>
4 #include <sys/param.h>
5
6 int
7 main( int argc, char **argv ) {
8 kstat_ctl_t *pc;
9 kstat_t *pk;
10 kstat_named_t *pn;
11
12 long hz;
13 ulong_t clk_intr;
14 double avenrun_1min;
15 double avenrun_5min;
16 double avenrun_15min;
17
18 ulong_t dd;
19 ulong_t hh;
20 ulong_t mm;
21 ulong_t ss;
22
23 hz = sysconf(_SC_CLK_TCK);
24 if ( !( pc = kstat_open() ) ) {
25 perror( "failed to open kstat" );
26 return -1;
27 }
28 if ( !( pk = kstat_lookup( pc, "unix", 0, "system_misc" ) ) ) {
29 perror( "failed to find system_misc" );
30 return -1;
31 }
32 if ( kstat_read( pc, pk, 0 ) < 0 ) {
33 perror( "failed to read kstat" );
34 return -1;
35 }
36 pn = (kstat_named_t*)kstat_data_lookup( pk, "clk_intr" );
37 clk_intr = pn->value.ul;
38 pn = (kstat_named_t*)kstat_data_lookup( pk, "avenrun_1min" );
39 avenrun_1min = ( (double)pn->value.ul ) / FSCALE;
40 pn = (kstat_named_t*)kstat_data_lookup( pk, "avenrun_5min" );
41 avenrun_5min = ( (double)pn->value.ul ) / FSCALE;
42 pn = (kstat_named_t*)kstat_data_lookup( pk, "avenrun_15min" );
43 avenrun_15min = ( (double)pn->value.ul ) / FSCALE;
44
45 dd = clk_intr / ( hz * 86400 ); clk_intr -= dd * hz * 86400;
46 hh = clk_intr / ( hz * 3600 ); clk_intr -= hh * hz * 3600;
47 mm = clk_intr / ( hz * 60 ); clk_intr -= mm * hz * 60;
48 ss = clk_intr / hz;
49
50 printf( "Up: %d day(s) %d hour(s) %d minute(s) %d second(s), ",
51 dd, hh, mm, ss );
52 printf( "load average: %.2f, %.2f, %.2f\n",
53 avenrun_1min, avenrun_5min, avenrun_15min );
54
55 kstat_close( pc );
56 return 0;
57 }
|