tags:

views:

123

answers:

3

Hi, How can I retrieve uptime under linux using C? (without using popen and/or /proc)

Thanks

+10  A: 

via top or via uptime.. but I don't know about any syscall, someone will for sure :)

uptime should be rather easy to parse.

Just stumbled into this:

#include <sys/sysinfo.h>

struct sysinfo info;
sysinfo(&info);
printf("Uptime = %d\n",info.uptime);
Jack
Horray for sysinfo() :) NB: `struct sysinfo` is rather 'shifty' between 2.4 (early) 2.4 (late) and 2.6. If your code is likely to be used for appliances, its handy to run build checks to see what members might be different.
Tim Post
+2  A: 

If its there and contains the member uptime, struct sysinfo is the preferred way to go, as Jack explained.

The other way is to read btime out of /proc/stat , then just subtract it from the current time. btime is just a UNIX epoch indicating when the kernel booted.

That gives you the # of seconds since boot, which you can then translate into years / months / days / hours / etc. This saves having to deal with strings in /proc/uptime. If btime isn't there, and struct sysinfo has no member named uptime, you have to parse /proc/uptime.

For modern kernels, sysinfo() should work just fine. Most things still running 2.4 (or earlier) out in the wild are appliances of some kind or other embedded systems.

Tim Post
A: 

To get the system start time in a more portable way, would be to use "who -b". To use this in a program you would have to spawn a shell and interpret its output. Unfortunately this seems the only place where such an information is available in POSIX, and this also only as an extension.

Jens Gustedt