Linux uses C language to obtain the system startup duration

Source: Internet
Author: User

Linux uses C language to obtain the system startup duration

The idea is to obtain the system startup duration by reading/proc/uptime.
Run cat/proc/uptime

Man proc shows the following information:
Why? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> placement/rj2ysfPtc2ztcS/1c/placement =" brush: java; ">#include #include #include #include struct timeval timeget(void){ struct timeval now; unsigned char timestr[60] = {0}; unsigned char uptimestr[30] = {0}; unsigned char * dotaddr; unsigned long second; char error = 0; FILE * timefile = NULL; timefile = fopen("/proc/uptime", "r"); if(!timefile) { printf("[%s:line:%d] error opening '/proc/uptime'",__FILE__,__LINE__); error = 1; goto out; } if( (fread(timestr, sizeof(char), 60, timefile)) == 0 ) { printf("[%s:line:%d] read '/proc/uptime' error",__FILE__,__LINE__); error = 1; goto out; } dotaddr = strchr(timestr, '.'); if((dotaddr - timestr + 2) < 30) memcpy(uptimestr, timestr, dotaddr - timestr + 2); else { printf("[%s:line:%d] uptime string is too long",__FILE__,__LINE__); error = 1; goto out; } uptimestr[dotaddr - timestr + 2] = '\0';out: if(error) { now.tv_sec = 0; now.tv_usec = 0; } else { now.tv_sec = atol(uptimestr); now.tv_usec = 0; } fclose(timefile); return now;}int main(){ struct timeval uptime; uptime = timeget(); printf("uptime = %lu\n", uptime.tv_sec); return 0;}

Running result:

Related Article

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.