Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What API do I call to get the system uptime?

Tags:

c

linux

uptime

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?

like image 957
Stéphane Avatar asked Oct 08 '09 21:10

Stéphane


People also ask

Which command displays the system uptime?

# uptime -h Usage: uptime [options] Options: -p, --pretty show uptime in pretty format -h, --help display this help and exit -s, --since system up since -V, --version output version information and exit For more details see uptime(1).

How is uptime displayed?

The uptime is normally displayed in days, hours, and minutes as appropriate. However, various options let you view the uptime only in days, hours, seconds, or milliseconds, as needed. The current time is the local time and is displayed in hh:mmmmmam/pm format.

What is the use of uptime command?

The uptime command gives you information about the current time, online users, how long your system has been up and running, and the system load average.

How do you read uptime proc?

Using /proc/uptimeThe first number is the total number of seconds the system has been up. The second number is how much of that time the machine has spent idle, in seconds. On multi core systems (and some Linux versions) the second number is the sum of the idle time accumulated by each CPU.


1 Answers

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!

like image 116
Kyle Smith Avatar answered Sep 28 '22 02:09

Kyle Smith