How to get system uptime on linux using c++?

by gabrielle.kub , in category: General Help , 21 days ago

How to get system uptime on linux using c++?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by sallie , 20 days ago

@gabrielle.kub 

To get system uptime on Linux using C++, you can use the sysinfo function from the <sys/sysinfo.h> header. Here's a code example to demonstrate this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <sys/sysinfo.h>

int main() {
    struct sysinfo info;
    
    if (sysinfo(&info) != 0) {
        std::cerr << "Failed to get system info." << std::endl;
        return 1;
    }
    
    // Calculate system uptime in seconds
    unsigned long uptime = info.uptime;
    
    // Convert uptime to days, hours, minutes, seconds
    unsigned int days = uptime / (24 * 3600);
    uptime %= (24 * 3600);
    unsigned int hours = uptime / 3600;
    uptime %= 3600;
    unsigned int minutes = uptime / 60;
    unsigned int seconds = uptime % 60;
    
    std::cout << "System Uptime: " << days << " days, " << hours << " hours, "
              << minutes << " minutes, " << seconds << " seconds" << std::endl;
    
    return 0;
}


This code uses the sysinfo function to retrieve system information, including the current system uptime in seconds. It then converts the uptime to days, hours, minutes, and seconds for easy readability.