Linux uses C language to get the system boot length

Source: Internet
Author: User

The idea is to get the system start-up time by reading/proc/uptime.
Using the command cat/proc/uptime

The following information can be seen through the man proc:
/proc/uptime:this file contains, numbers:the uptime of the system (seconds), and the amount of time spent in idle proc ESS (seconds).
The first is the system's startup time, and the second is the idle time of the system. Two units are in seconds.

#include <stdio.h>#include <string.h>#include <sys/time.h>#include <stdlib.h>structTimeval Timeget (void){structTimeval now;unsigned Chartimestr[ -] = {0};unsigned Charuptimestr[ -] = {0};unsigned Char* DOTADDR;unsigned LongSecondCharError =0;    FILE * Timefile = NULL; Timefile = fopen ("/proc/uptime","R");if(!timefile) {printf("[%s:line:%d] Error opening '/proc/uptime '", __file__,__line__); Error =1;GotoOut }if(Fread (TIMESTR,sizeof(Char), -, timefile)) = =0)    {printf("[%s:line:%d] read '/proc/uptime ' ERROR", __file__,__line__); Error =1;GotoOut } dotaddr =STRCHR(Timestr,'. ');if((Dotaddr-timestr +2) < -)memcpy(Uptimestr, TIMESTR, Dotaddr-timestr +2);Else{printf("[%s:line:%d] uptime string is too long", __file__,__line__); Error =1;GotoOut } Uptimestr[dotaddr-timestr +2] =' + '; Out:if(Error) {now.tv_sec =0; Now.tv_usec =0; }Else{now.tv_sec = Atol (UPTIMESTR); Now.tv_usec =0; } fclose (Timefile);returnNow;}intMain () {structTimeval uptime; Uptime = Timeget ();printf("uptime =%lu\n", uptime.tv_sec);return 0;}

Operation Result:

Linux uses C language to get the system boot length

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.