当前位置: 技术问答>linux和unix
怎么将这段JAVA代码换成C语言,实现同样的功能,就是查看进程内存?
来源: 互联网 发布时间:2016-08-10
本文导语: 通过读取/PROC/STAT得到每一个数据,怎么通过C实现,这个是JAVA? public static float getCpuInfo() throws IOException, InterruptedException { File file = new File("/proc/stat"); BufferedReader br = new BufferedReader (new InputStreamReade...
通过读取/PROC/STAT得到每一个数据,怎么通过C实现,这个是JAVA?
public static float getCpuInfo() throws IOException,
InterruptedException
{
File file = new File("/proc/stat");
BufferedReader br = new BufferedReader (new
InputStreamReader(new FileInputStream(file)));
StringTokenizer token = new StringTokenizer(br.readLine
());
token.nextToken();
int user1 = Integer.parseInt(token.nextToken());
int nice1 = Integer.parseInt(token.nextToken());
int sys1 = Integer.parseInt(token.nextToken());
int idle1 = Integer.parseInt(token.nextToken());
Thread.sleep(1000);
br = new BufferedReader( new InputStreamReader(new
FileInputStream(file)));
token = new StringTokenizer(br.readLine());
token.nextToken();
int user2 = Integer.parseInt(token.nextToken());
int nice2 = Integer.parseInt(token.nextToken());
int sys2 = Integer.parseInt(token.nextToken());
int idle2 = Integer.parseInt(token.nextToken());
return (float) ((user2 + sys2 + nice2) - ( user1 + sys1
+ nice1))/(float)
((user2 + sys2 + nice2 + idle2) - ( user1 + sys1 + nice1
+idle1));
}
public static float getCpuInfo() throws IOException,
InterruptedException
{
File file = new File("/proc/stat");
BufferedReader br = new BufferedReader (new
InputStreamReader(new FileInputStream(file)));
StringTokenizer token = new StringTokenizer(br.readLine
());
token.nextToken();
int user1 = Integer.parseInt(token.nextToken());
int nice1 = Integer.parseInt(token.nextToken());
int sys1 = Integer.parseInt(token.nextToken());
int idle1 = Integer.parseInt(token.nextToken());
Thread.sleep(1000);
br = new BufferedReader( new InputStreamReader(new
FileInputStream(file)));
token = new StringTokenizer(br.readLine());
token.nextToken();
int user2 = Integer.parseInt(token.nextToken());
int nice2 = Integer.parseInt(token.nextToken());
int sys2 = Integer.parseInt(token.nextToken());
int idle2 = Integer.parseInt(token.nextToken());
return (float) ((user2 + sys2 + nice2) - ( user1 + sys1
+ nice1))/(float)
((user2 + sys2 + nice2 + idle2) - ( user1 + sys1 + nice1
+idle1));
}
|
没有做错误处理。
#include
#include
#include
#include
float getCpuInfo()
{
int user1, nice1, sys1, idle1;
int user2, nice2, sys2, idle2;
char line[80]={0};
FILE *fp = fopen("/proc/stat", "r");
fgets(line, 80, fp);
sscanf(strchr(line, ' '), "%d %d %d %d", &user1, &nice1, &sys1, &idle1);
//printf("%d %d %d %dn",user1, nice1, sys1, idle1);
fclose(fp);
sleep(1);
fp = fopen("/proc/stat", "r");
fgets(line, 80, fp);
sscanf(strchr(line, ' '), "%d %d %d %d", &user2, &nice2, &sys2, &idle2);
fclose(fp);
return (float)((user2 + sys2 + nice2) -(user1 + sys1 + nice1)) /
((user2 + sys2 + nice2 + idle2) - (user1 + sys1 + nice1 + idle1));
}
int main()
{
printf("%fn", getCpuInfo());
return 0;
}