summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/OR_USING_C/c.1.c
blob: 257f3c8854198cd8585dd6e8d6a79f7b542ec944 (plain)
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
#include <sys/param.h>
#include <sys/time.h>
#include <sys/file.h>
#include <nlist.h>
#include <stdio.h>

/*
 * We declare an array of nlist structures,
 * and initialize them to the names of the
 * variables we want.  The last entry is
 * to terminate the list.
 */
struct nlist nl[] = {
#define X_BOOTTIME     0
    {    "_boottime" },
#define X_AVENRUN      1
    {    "_avenrun"  },
    {    0           }
};

main()
{
    int kmem;
    char *ctime();
    struct timeval boottime;

    /*
     * _avenrun is an array of three numbers.
     * Most machines use floating point; Sun
     * workstations use long integers.
     */
#ifdef sun
    long avenrun[3];
#else
    double avenrun[3];
#endif

    /*
     * Open kernel memory.
     */
    if ((kmem = open("/dev/kmem", O_RDONLY)) < 0) {
        perror("/dev/kmem");
        exit(1);
    }

    /*
     * Read the kernel namelist.  If nl[0].n_type is
     * 0 after this, then the call to nlist() failed.
     */
    if ((nlist("/vmunix", nl) < 0) || (nl[0].n_type == 0)) {
        fprintf(stderr, "/vmunix: no namelist\n");
        exit(1);
    }

    /*
     * Read the _boottime variable.  We do this by
     * seeking through memory to the address found
     * by nlist, and then reading.
     */
    lseek(kmem, (long) nl[X_BOOTTIME].n_value, L_SET);
    read(kmem, (char *) &boottime, sizeof(boottime));
    /*
     * Read the load averages.
     */
    lseek(kmem, (long) nl[X_AVENRUN].n_value, L_SET);
    read(kmem, (char *) avenrun, sizeof(avenrun));

    /*
     * Now print the system boot time.
     */
    printf("System booted at %s\n", ctime(&boottime.tv_sec));

    /*
     * Print the load averages.  Sun workstations use
     * FSCALE to convert the long integers to floating
     * point.  The three elements of _avenrun are the
     * load average over the past one, five, and ten
     * minutes.
     */
#ifdef sun
    printf("One minute load average:  %.2f\n",
        (double) avenrun[0] / FSCALE);
    printf("Five minute load average: %.2f\n",
        (double) avenrun[1] / FSCALE);
    printf("Ten minute load average:  %.2f\n",
        (double) avenrun[2] / FSCALE);
#else
    printf("One minute load average:  %.2f\n", avenrun[0]);
    printf("Five minute load average: %.2f\n", avenrun[1]);
    printf("Ten minute load average:  %.2f\n", avenrun[2]);
#endif

    close(kmem);
    exit(0);
}