Created
July 5, 2023 04:58
-
-
Save spiritedRunning/401508290c16f92321edf5405dfbd412 to your computer and use it in GitHub Desktop.
linux system state
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <dirent.h> | |
#include <string.h> | |
void get_cpu_load() { | |
FILE* fp = popen("uptime | awk '{print $(NF-2)}'", "r"); | |
if (fp == NULL) { | |
printf("Failed to get CPU load.\n"); | |
return; | |
} | |
char load[50]; | |
fgets(load, sizeof(load), fp); | |
pclose(fp); | |
printf("Current CPU load: %s\n", load); | |
} | |
void get_cpu_temperature() { | |
FILE* fp = popen("echo $[$(cat /sys/class/thermal/thermal_zone0/temp)/1000]°", "r"); | |
if (fp == NULL) { | |
printf("Failed to get CPU temperature.\n"); | |
return; | |
} | |
char temperature[50]; | |
fgets(temperature, sizeof(temperature), fp); | |
pclose(fp); | |
printf("Current CPU temperature: %s\n", temperature); | |
} | |
void get_disk_usage() { | |
FILE* fp = popen("df -h | awk '/\\/$/ {print $5}'", "r"); | |
if (fp == NULL) { | |
printf("Failed to get disk usage.\n"); | |
return; | |
} | |
char usage[50]; | |
fgets(usage, sizeof(usage), fp); | |
pclose(fp); | |
printf("Disk usage in /: %s\n", usage); | |
} | |
void get_all_processes() { | |
FILE* fp = popen("ps -A -o pid,comm", "r"); | |
if (fp == NULL) { | |
printf("Failed to get all processes.\n"); | |
return; | |
} | |
char buffer[256]; | |
fgets(buffer, sizeof(buffer), fp); // Skip the header line | |
while (fgets(buffer, sizeof(buffer), fp) != NULL) { | |
int pid; | |
char process_name[256]; | |
sscanf(buffer, "%d %[^\n]", &pid, process_name); | |
printf("PID: %d, Name: %s\n", pid, process_name); | |
} | |
pclose(fp); | |
} | |
int get_network_usage() { | |
char pingCmd[256]; | |
char buf[256]; | |
FILE *fp; | |
snprintf(pingCmd, sizeof(pingCmd), "ping -c 4 www.baidu.com &"); | |
if ((fp = popen(pingCmd, "r")) == NULL) { | |
perror("popen"); | |
return -1; | |
} | |
while (fgets(buf, sizeof(buf), fp) != NULL) { | |
printf("%s", buf); | |
} | |
if (pclose(fp) == -1) { | |
perror("pclose"); | |
return -1; | |
} | |
return 0; | |
} | |
int main(int argc, char* argv[]) { | |
get_cpu_load(); | |
get_cpu_temperature(); | |
get_disk_usage(); | |
get_all_processes(); | |
get_network_usage(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment