1
/* $Id: plugin_uptime.c 840 2007-09-09 12:17:42Z michael $
2
* $URL: https://ssl.bulix.org/svn/lcd4linux/trunk/plugin_uptime.c $
6
* Copyright (C) 2003 Michael Reinelt <michael@reinelt.co.at>
7
* Copyright (C) 2004 The LCD4Linux Team <lcd4linux-devel@users.sourceforge.net>
9
* This file is part of LCD4Linux.
11
* LCD4Linux is free software; you can redistribute it and/or modify
12
* it under the terms of the GNU General Public License as published by
13
* the Free Software Foundation; either version 2, or (at your option)
16
* LCD4Linux is distributed in the hope that it will be useful,
17
* but WITHOUT ANY WARRANTY; without even the implied warranty of
18
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19
* GNU General Public License for more details.
21
* You should have received a copy of the GNU General Public License
22
* along with this program; if not, write to the Free Software
23
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
30
* int plugin_init_uptime (void)
31
* adds functions for uptime
43
#include <sys/types.h>
54
static char *itoa(char *buffer, const size_t size, unsigned int value)
59
if (buffer == NULL || size < 2)
62
/* p points to last char */
63
p = buffer + size - 1;
65
/* set terminating zero */
69
*--p = value % 10 + '0';
71
} while (value != 0 && p > buffer);
77
char *struptime(const unsigned int uptime, const char *format)
79
static char string[256];
88
/* leave room for terminating zero */
89
size = sizeof(string) - 1;
96
if (strchr("sSmMhHd", *src) != NULL) {
98
unsigned int value = 0;
112
value = (uptime / 60) % 60;
116
value = uptime / 60 / 60;
119
value = (uptime / 60 / 60) % 24;
123
value = uptime / 60 / 60 / 24;
127
if (leading_zero && value < 10) {
132
s = itoa(buffer, sizeof(buffer), value);
133
while (len < size && *s != '\0') {
138
} else if (*src == '%') {
156
/* enforce terminating zero */
157
if (len >= size && *(dst - 1) != '\0') {
166
double getuptime(void)
172
fd = open("/proc/uptime", O_RDONLY);
176
lseek(fd, 0, SEEK_SET);
178
i = read(fd, buffer, sizeof(buffer) - 1);
182
buffer[i - 1] = '\0';
184
/* ignore the 2nd value from /proc/uptime */
185
return strtod(buffer, NULL);
189
static void my_uptime(RESULT * result, const int argc, RESULT * argv[])
192
static double uptime = 0.0;
193
static struct timeval last_value;
197
error("uptime(): wrong number of parameters");
198
SetResult(&result, R_STRING, "");
202
gettimeofday(&now, NULL);
204
age = (now.tv_sec - last_value.tv_sec) * 1000 + (now.tv_usec - last_value.tv_usec) / 1000;
205
/* reread every 100 msec only */
206
if (fd == -2 || age == 0 || age > 100) {
207
uptime = getuptime();
209
error("parse(/proc/uptime) failed!");
210
SetResult(&result, R_STRING, "");
218
SetResult(&result, R_NUMBER, &uptime);
220
SetResult(&result, R_STRING, struptime(uptime, R2S(argv[0])));
227
int plugin_init_uptime(void)
229
AddFunction("uptime", -1, my_uptime);
233
void plugin_exit_uptime(void)