Write a c program to report behavior of Linux kernel including information on configured memory, amount of free and used memory. (memory information)
To report memory information in a Linux system, including configured memory, free memory, and used memory, you can read from the /proc/meminfo file. Below is a C program that retrieves and displays this information.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char line[256];
// Open /proc/meminfo for reading
fp = fopen("/proc/meminfo", "r");
if (fp == NULL) {
perror("Failed to open /proc/meminfo");
exit(EXIT_FAILURE);
}
printf("Memory Information:\n");
// Read lines from /proc/meminfo
while (fgets(line, sizeof(line), fp) != NULL) {
// Print specific memory information
if (strncmp(line, "MemTotal", 8) == 0 ||
strncmp(line, "MemFree", 7) == 0 ||
strncmp(line, "MemAvailable", 12) == 0 ||
strncmp(line, "Buffers", 7) == 0 ||
strncmp(line, "Cached", 6) == 0) {
printf("%s", line);
}
}
fclose(fp);
return 0;
}