Reputation: 91
I need to find the system time since power is applied on a linux machine in my c code. Functions like 'time()' and gettimeofday() return the time since epoch and not since power on. How do I find the time or number of clock ticks since power on?
Thanks in advance!
Upvotes: 5
Views: 12178
Reputation: 51850
This information is provided through the /proc
filesystem API. Specifically, /proc/uptime
. In C, just open it as a normal file and read one floating point number from it. It will be the amount of seconds since power on. If you read another FP value, it will be how many seconds the system has spent in total being idle. You're only interested in the first number though.
Example:
float uptime;
FILE* proc_uptime_file = fopen("/proc/uptime", "r");
fscanf(proc_uptime_file, "%f", &uptime);
This value is in seconds, floating point.
You can convert it back to clock ticks:
uptime * sysconfig(_SC_CLK_TCK);
Upvotes: 10
Reputation: 1277
See: Wgat API do I call to get the System Time
Please see sysinfo() in
sys/sysinfo.h
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 */
};
Upvotes: 3
Reputation: 2223
If you want to know the C API,
this question is a possible duplicate of What API do I call to get the system uptime?
If you want to know uptime via shell, use uptime command.
$uptime
Upvotes: 2