pid.h
char *mystrcpy(char*,char*);
int readpidmax();
void init();
int readprocessnum();
int increasemax();
int needincrease();
pid.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/time.h>
#include <string.h>
#include <unistd.h>
#include "pid.h"
//阈值
#define alarm 0.05
//pdimaxnum and pidcurrentnum的位数
#define charnum 10
char *pidmaxnum;
int pidmax;
char *pidcurrentnum;
char *temppidnum;
//读取当前进程数的缓冲区
char buffer[2000];
//读取当前进程数的缓冲区的大小
#define processbufferisze 2000
char* mystrcpy(char *str1,char *str2){
char *end=strchr(str2,'\0');
int l=end-str2;
memset(str1,'\0',charnum);
memcpy(str1,str2,l);
return str1;
}
//读取当前的允许的最大的进程数
int readpidmax(){
FILE *f=fopen("/proc/sys/kernel/pid_max","rb");
if(f==NULL){
printf("error:open file rb mode\n");
exit(1);
}
//10个字符肯定能够放下数字
fgets(pidmaxnum,charnum,f);
mystrcpy(temppidnum,pidmaxnum);
pidmax=atoi(temppidnum);
fclose(f);
}
//初始化
void init(){
pidmax=0;
pidmaxnum=(char*)malloc(charnum);
pidcurrentnum=(char*)malloc(charnum);
temppidnum=(char*)malloc(charnum);
readpidmax();
}
//读取当前的进程数
int readprocessnum(){
int num=0;
FILE* fd=fopen("/proc/stat","rb");
if(fd==NULL){
printf("erorrr\n");
}
num=fread(buffer,sizeof(char),processbufferisze,fd);
//关闭文件
fclose(fd);
char *str=malloc(num);
strncpy(str,buffer,num);
char *delim="\n";
char *delim2=" ";
char *p;
//存放一行信息
char *substr;
char *subp;
p=strtok(str,delim);
int index=0;
char *substrs[12];
int nums=0;
do{
substrs[nums]=p;
nums++;
}
while(p=strtok(NULL,delim));
int index4=0;
//通过对/proc/stat文件的了解我们知道第八行就是我们需要的数据所在的行
char *substrpt=strtok(substrs[8],delim2);
int interindex=0;
do{
if(interindex==1){
memset(pidcurrentnum,'\0',charnum);//将存储当前进程数的buffer清零
memcpy(pidcurrentnum,substrpt,strlen(substrpt));//将读到的进程数拷贝到处理buffer中
//printf("pidcurrentnum is: %s\n",pidcurrentnum);
break;
}
interindex++;
}
while(substrpt=strtok(NULL,delim2));
free(str);
}
//对当前允许的最大进程数加一
//需要超级用户权限!!!!!!!!!!!!!!!!!!!!!!!!1
int increasemax(){
pidmax++;//最大进程数加一
char numstr[6];
//将integer转化为string
sprintf(numstr,"%d",pidmax);
FILE* f=fopen("/proc/sys/kernel/pid_max","wb");
if(f==NULL){
printf("%s\n","errorr:open file wb modes");
exit(1);
}
printf("numstr is : %s %d\n",numstr,strlen(numstr));
//fwrite(numstr,sizeof(char),6,f);//写入
fputs(numstr,f);
fclose(f);
}
//判断是否需要对当前允许的最大进程数加一
int needincrease(){
//读取当前进程数
readprocessnum();
int current=atoi(pidcurrentnum);
printf("max is:%d current is:%d\n",pidmax,current);
//当前进程数是否大于最大进程数*阈值
if(current>pidmax*alarm){
return 1;
}
return 0;
}
int main(){
init();
int loop=0;
while(1){
printf("loop %d begin.###################################################\n",loop);
if(needincrease()==1){
increasemax();
printf("%s\n","need increase,and increased");
}
else{
printf("%s\n","need not increase");
}
printf("loop %d end ###################################################\n\n",loop);
sleep(4);
loop++;
}
return 0;
}
hotkey
最新推荐文章于 2021-08-18 09:49:59 发布