vi check_open_file.c (仅限linux系统使用)
#include <stdio.h> #include <stdlib.h> #include <string.h> #define OK 0 #define WARNING 1 #define CRITICAL 2 #define UNKNOWN 3 #define LEN 1000 #define FILE_NR "/proc/sys/fs/file-nr" int exitstatus=OK; char *exit_status[4]={"OK","WARNING","CRITICAL","UNKNOWN"}; char status_information[LEN]; char performance_data[LEN]; int parse_cmd() { int ret=0; FILE *fp; char readbuf[LEN]; int i; char *p,*str; float used_percent=0; char used_handle[LEN]={0},free_handle[LEN]={0},max_handle[LEN]={0}; fp=fopen(FILE_NR,"r"); if(fp==NULL) { // fprintf(stderr,"fopen() error.\n"); sprintf(status_information,"File not exist, used_handle=%s max_handle=%s used_percent=%.0f%%","0","0",used_percent*100); sprintf(performance_data,"used_handle=%s;;;; max_handle=%s;;;; used_percent=%.0f%%;30;50;;","0","0",used_percent*100); exitstatus=CRITICAL; printf("%s: %s | %s\n",exit_status[exitstatus],status_information,performance_data); exit(exitstatus); } str=fgets(readbuf,LEN,fp); if(str==NULL) { fprintf(stderr,"fgets() error.\n"); return -1; } // printf("readbuf=%s",readbuf); ret=sscanf(readbuf,"%s\t%s\t%s",used_handle,free_handle,max_handle); // printf("sscanf ret=%d\n",ret); // printf("used_handle=%s,free_handle=%s,max_handle=%s\n",used_handle,free_handle,max_handle); used_percent=(float)(atoi(used_handle)/(float)atoi(max_handle)); // printf("used_percent=%f\n",used_percent); // printf("used_percent=%.0f\n",used_percent*100); if(used_percent>=0 && used_percent<30) { exitstatus=OK; } else if(used_percent>=30 && used_percent<50) { exitstatus=WARNING; } else if(used_percent>=50 && used_percent<=100) { exitstatus=CRITICAL; } else { exitstatus=CRITICAL; } sprintf(status_information,"used_handle=%s max_handle=%s used_percent=%.0f%%",used_handle,max_handle,used_percent*100); sprintf(performance_data,"used_handle=%s;;;; max_handle=%s;;;; used_percent=%.0f%%;30;50;;",used_handle,max_handle,used_percent*100); ret=fclose(fp); if(ret==EOF) { fprintf(stderr,"fclose() error.\n"); return -1; } // while(fgets(readbuf,1024,fp)!=NULL) { /* for(p=strtok(readbuf," ");p;p=strtok(NULL," ")) { // str=p; sprintf(status_information,"active call=%s",p); sprintf(performance_data,"call=%s;;;;",p); break; } break; */ return 0; } int main() { int ret; ret=parse_cmd(); if(ret!=0) { fprintf(stderr,"parse_cmd() error.\n"); // exitstatus=CRITICAL; // printf("%s: - %s | %s\n",exit_status[exitstatus],status_information,performance_data); // exit(-1); } printf("%s: %s | %s\n",exit_status[exitstatus],status_information,performance_data); return exitstatus; }