tags:

views:

764

answers:

3

I would like to get the system uptime from within a C application running on a linux-based system. I don't want to call uptime(1) and parse the output, I'd like to call the underlying C API I suspect exists. Anyone know if there is such a call, or does uptime(1) simply process records obtained from wtmp?

+5  A: 

Read the file /proc/uptime and take the first decimal number as the uptime in seconds.

From man 5 proc:

   /proc/uptime
          This file contains two numbers: the uptime of the  system  (sec‐
          onds), and the amount of time spent in idle process (seconds).
bdonlan
...and if you `strace` the `uptime(1)` command, you'll see that it does just that.
caf
caf: on linux machines, BSD machines generally uses "current time - syctl kern.boottime"
Wergan
@caf, `uptime(1)` does a lot more than just that, so it can be a bit hard to find :)
bdonlan
+4  A: 

The system call you're looking for is sysinfo().

It's defined in sys/sysinfo.h

Its signature is: int sysinfo(struct sysinfo *info)

Since kernel 2.4, the structure has looked like this:

struct sysinfo {
    long uptime;             /* Seconds since boot */
    unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
    unsigned long totalram;  /* Total usable main memory size */
    unsigned long freeram;   /* Available memory size */
    unsigned long sharedram; /* Amount of shared memory */
    unsigned long bufferram; /* Memory used by buffers */
    unsigned long totalswap; /* Total swap space size */
    unsigned long freeswap;  /* swap space still available */
    unsigned short procs;    /* Number of current processes */
    unsigned long totalhigh; /* Total high memory size */
    unsigned long freehigh;  /* Available high memory size */
    unsigned int mem_unit;   /* Memory unit size in bytes */
    char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */
};

Have fun!

Kyle Smith
I'd implemented reading /proc/uptime as bdonlan suggested above, but calling an API versus reading a "file" is exactly what I wanted. Thank you!
Stéphane
A: 

That would be something like this.

#include <stdio.h>
#include <errno.h>
#include <linux/unistd.h>       /* for _syscallX macros/related stuff */
#include <linux/kernel.h>       /* for struct sysinfo */

long get_uptime()
{
    struct sysinfo s_info;
    int error;
    error = sysinfo(&s_info);
    if(error != 0)
    {
        printf("code error = %d\n", error);
    }
    return s_info.uptime;
}
Johan