我正在嘗試創建一個程式監控系統引數,例如: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 命令。你能幫我解釋一下為什么嗎?以及這種情況的解決方案。
uj5u.com熱心網友回復:
return value;
pclose(fp);
所以pclose(fp)永遠不會被呼叫。因此,您FILE在每次呼叫時都會泄漏資源(流、檔案描述符、子行程等),最終您會耗盡資源,從而popen失敗。
如果您使用pclose得當,則可以呼叫 的次數沒有限制popen。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/319093.html
