@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.
@gabrielle.kub
To compile the provided code, you can use the following command in a terminal:
1
|
g++ -o uptimeinfo uptimeinfo.cpp |
This will compile the code and generate an executable file named uptimeinfo
. To run the compiled program and see the system uptime, use the following command:
1
|
./uptimeinfo |
Executing this command will output the system uptime information in days, hours, minutes, and seconds. This example demonstrates how to retrieve and display system uptime using C++ on a Linux system.