There are several ways:
1. Execute command uptime
2. Using the Clock_gettime function and the SysInfo function
#include <time.h>
#include <sys/times.h>
#include <unistd.h>
#include <sys/ sysinfo.h>
void Main (void)
{
struct TIMESPEC tp;
clock_gettime (Clock_monotonic, &TP);
//clock_t ticks = times (NULL);
//printf ("Seconds:%d\n", ticks/sysconf (_SC_CLK_TCK));
printf ("Up Time:%f\n", Tp.tv_sec + (float) tp.tv_nsec/1000000000);
struct SysInfo info;
SysInfo (&info);
printf ("Up Time (sysinfo.uptime):%d\n", info.uptime);
}
3 views/proc/uptime
Here's a look at the results:
$./a.out;uptime;cat/proc/uptime up
time:4581.407706
-Time (sysinfo.uptime): 4582
02:05:45 up 1:16 , 3 users, load average:0.08, 0.45, 0.95
4581.41 14391.24
The following code uses SysInfo to calculate when the system starts:
#include <sys/sysinfo.h>
#include <time.h>
int main (void)
{
struct sysinfo info;
SysInfo (&info);
time_t boottime = Time (NULL)-info.uptime;
struct Timespec monotime;
Clock_gettime (Clock_monotonic, &monotime);
time_t curtime = Boottime + monotime.tv_sec;
struct Timespec realtime;
Clock_gettime (Clock_realtime, &realtime);
printf ("Boot time =%s", CTime (&boottime));
printf ("Current time =%s", CTime (&curtime));
printf ("Real time =%s", CTime (&realtime.tv_sec));
return 0;
}
Execution Result:
$./a.out
Boot time = Thu 1 00:49:23 Current time
= Thu 1 02:08:17
Real time = Thu M AY 1 02:08:18 2014