Write a program in C++ to display the following information from Linux. 1. Gener
ID: 641588 • Letter: W
Question
Write a program in C++ to display the following information from Linux.
1. General information.
In this section you will assemble some basic facts about the system
a. Machine name (hostname) # get this information from /proc/sys/kernel/hostname
b. System date and time # get this information from /proc/driver/rtc
c. Kernel version # get this information from /proc/version
d. Memory usage (used and free memory) # get this information from /proc/meminfo
2. Time information.
In this section you will print out how long the system has been up and how busy it has been.
a. Duration of uptime # get these information from /proc/uptime
b. Duration of idletime
The skeleton of the program
(1) read file
Explanation / Answer
Here is the program for obtaining all the values from the 'Proc' Pseudo-Filesystem.
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int main()
{
float uptime, idletime;
FILE* fp;
fp = fopen("/proc/uptime","r");
fscanf(fp,"%f %f",&uptime, &idletime);
printf("Uptime: %.2f ",uptime);
printf("Idletime: %.2f ",idletime);
/*
printf("Seconds %d: ",uptime%60);
uptime = uptime /60;
printf("Minutes %d: ",uptime%60);
uptime = uptime /60;
printf("Hours %d: ",uptime%60);
*/
fclose(fp);
char hostname[100];
fp = fopen("/proc/sys/kernel/hostname", "r");
fscanf(fp, "%s", &hostname);
printf("Hostname: %s ", hostname);
fclose(fp);
fp = fopen("/proc/version", "r");
int i = 0;
char a[1000][100];
while(fscanf(fp,"%s",&a[++i]) != EOF)
{
//printf("%s", a[i-1]);
}
fclose(fp);
int n=i;
for(i=1;i<=n;i++)
{
if(!strcmp("Linux",a[i]) && !strcmp("version",a[i+1]) )
{
printf("Linux Version: %s ", a[i+2]);
break;
}
}
fp = fopen("/proc/meminfo", "r");
i = 0;
char mem[1000][100];
while(fscanf(fp,"%s",&mem[++i]) != EOF)
{
}
fclose(fp);
n=i;
for(i=1;i<=n;i++)
{
if(!strcmp("MemFree:",mem[i]) )
{
printf("Memory Free: %s kB ", mem[i+1]);
break;
}
}
fp = fopen("/proc/driver/rtc", "r");
i = 0;
char rtc[1000][100];
while(fscanf(fp,"%s",&rtc[++i]) != EOF)
{
}
fclose(fp);
n=i;
for(i=1;i<=n;i++)
{
if(!strcmp("rtc_time",rtc[i]) )
{
printf("TIME: %s ", rtc[i+2]);
}
if(!strcmp("rtc_date",rtc[i]) )
{
printf("DATE: %s ", rtc[i+2]);
break;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.