2 * gloadavg.c - get load average for Linux
3 * Copyright (C) 1993 Thomas Koenig
4 * Copyright 2000-2012 Thibault Godouet <fcron@free.fr>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 #ifndef _POSIX_SOURCE /* Don't redefine if already exists */
22 #define _POSIX_SOURCE 1
29 #include "getloadavg.h"
31 /* Global functions */
38 getloadavg(double *result, int n)
39 /* return the current load average as a floating point number,
40 * the number of load averages read, or <0 for error
46 kstat_named_t knm_buf[20];
57 for (ksp = kc->kc_chain; ksp != NULL; ksp = ksp->ks_next) {
58 if (strcmp(ksp->ks_name, "system_misc") == 0) {
59 kstat_read(kc, ksp, &knm_buf);
60 for (cnt=0; cnt<ksp->ks_ndata; cnt++) {
62 if (strcmp(knm->name,"avenrun_1min") == 0) {
63 result[0] = knm->value.ui32 / 256.0;
66 else if (strcmp(knm->name,"avenrun_5min") == 0) {
67 result[1] = knm->value.ui32 / 256.0;
70 else if (strcmp(knm->name,"avenrun_15min") == 0) {
71 result[2] = knm->value.ui32 / 256.0;
82 #else /* def HAVE_KSTAT */
85 getloadavg(double *result, int n)
86 /* return the current load average as a floating point number,
87 * the number of load averages read, or <0 for error
96 if ((fp = fopen(PROC "/loadavg", "r")) == NULL) {
97 error_e("could not open '"PROC"/loadavg'"
98 " (make sure procfs is mounted)");
102 for (i = 0; i < n; i++) {
103 if (fscanf(fp, "%lf", result) != 1)
110 return (i<0) ? i : i;
113 #endif /* def HAVE_KSTAT */