2 * uptime.c - display system uptime
3 * Copyright (C) 2012 Craig Small <csmall-procps@enc.com.au>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 #include "fileutils.h"
30 #include "proc/sysinfo.h"
31 #include "proc/whattime.h"
32 #include "proc/version.h"
34 static void print_uptime_since()
36 double now, uptime_secs, idle_secs;
41 /* Get the current time and convert it to a double */
42 if (gettimeofday(&tim, NULL) != 0)
43 xerr(EXIT_FAILURE, "gettimeofday");
44 now = tim.tv_sec + (tim.tv_usec / 1000000.0);
46 /* Get the uptime and calculate when that was */
47 if (uptime(&uptime_secs, &idle_secs) == 0)
48 xerrx(EXIT_FAILURE, "uptime");
49 up_since_secs = (time_t) ((now - uptime_secs) + 0.5);
52 if ((up_since = localtime(&up_since_secs)) == NULL)
53 xerrx(EXIT_FAILURE, "localtime");
54 printf("%04d-%02d-%02d %02d:%02d:%02d\n",
55 up_since->tm_year + 1900, up_since->tm_mon + 1, up_since->tm_mday,
56 up_since->tm_hour, up_since->tm_min, up_since->tm_sec);
59 static void __attribute__ ((__noreturn__)) usage(FILE * out)
61 fputs(USAGE_HEADER, out);
62 fprintf(out, _(" %s [options]\n"), program_invocation_short_name);
63 fputs(USAGE_OPTIONS, out);
64 fputs(_(" -p, --pretty show uptime in pretty format\n"), out);
65 fputs(USAGE_HELP, out);
66 fputs(_(" -s, --since system up since\n"), out);
67 fputs(USAGE_VERSION, out);
68 fprintf(out, USAGE_MAN_TAIL("uptime(1)"));
70 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
73 int main(int argc, char **argv)
77 static const struct option longopts[] = {
78 {"pretty", no_argument, NULL, 'p'},
79 {"help", no_argument, NULL, 'h'},
80 {"since", no_argument, NULL, 's'},
81 {"version", no_argument, NULL, 'V'},
85 #ifdef HAVE_PROGRAM_INVOCATION_NAME
86 program_invocation_name = program_invocation_short_name;
88 setlocale (LC_ALL, "");
89 bindtextdomain(PACKAGE, LOCALEDIR);
93 while ((c = getopt_long(argc, argv, "phsV", longopts, NULL)) != -1)
101 print_uptime_since();
104 printf(PROCPS_NG_VERSION);