[英]Issue when opening a system file Linux in for loop
我正在尝试创建一个程序监控系统参数,例如:CPU 使用率百分比、Ram 使用率百分比,并在百分比超过 80% 时发送警告日志。 我在读取 CPU 百分比时的解决方案是使用mpstat
或 cat /proc/stat 这样的:
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
}
}
}
问题是当我在几分钟后运行程序时,我将无法打开文件,指针fp
为NULL
。 我认为 Linux 会阻止程序打开文件的次数过多,或者可能无法多次运行 bash 命令。 你能帮我解释一下为什么吗? 以及这种情况的解决方案。
return value;
pclose(fp);
所以pclose(fp)
永远不会被调用。 因此,您在每次调用时都会泄漏资源( FILE
流、文件描述符、子进程等),最终您会耗尽资源,因此popen
失败。
如果pclose
正确,则可以调用popen
次数没有限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.