I am trying to create a program monitor system parameter like: CPU usage percent, Ram usage percent and send a warning log when the percent is over 80%. My solution when reading CPU percent is using mpstat
or cat the /proc/stat like this:
unsigned int get_system_value(char *command)
{
FILE *fp;
char value_string[1024];
fflush(fp);
fp = popen(command, "r"); /* The issue is here */
if (fp == NULL) {
printf("Failed to check command system \n" );
return -1;
}
while (fgets(value_string, sizeof(value_string), fp) != NULL);
unsigned int value = atoi(value_string);
return value;
pclose(fp);
}
void *get_sys_stat(void* arg)
{
float cpu_percent = 0;
int cpu_high_flag = 0;
int cpu_too_high_flag = 0;
while(1) {
// cpu_percent = get_system_value("mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12"" }'"); // using mpstat
cpu_percent = get_system_value("grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage}'"); // using cat /proc/stat
if (cpu_percent > 80) {
trap_cpu_high(ar_general_config[0].general_id); // send warning log
}
}
}
And the issue is when i run program after a few minutes i will can not open the file, the pointer fp
is NULL
. I guest that Linux prevent a program open a file too many times or maybe can not run a bash command too many times. Can you help me explain why ? and a solution for this case.