[시스템] CPU 사용량 측정 소스 코드

CPU Tick count 를 이용한 일반적인 CPU점유율 모니터를 만들어 봤습니다.

아래 파일을 “cpuusage.c” 로 저장후 다음과 같이 컴파일 합니다.

bash# gcc -s -O2 -Wall -I. -ansi -o cpuusage cpuusage.c

====================== [ 절취선 ] ============================

/*

Copyright (c) 2002 Information Equipment co.,LTD.

All Right Reserved.

Code by JaeHyuk Cho < minzkn@infoeq.co.kr >

– Simple is best

– [SEE] Linux kernel /usr/src/linux/fs/proc/proc_misc.c FUNCTION(kstat_read_proc)

*/

#include <stdio.h>

#include <unistd.h>

#include <fcntl.h>

#include <string.h>

#define DEF_PROCSTAT_BUFFER_SIZE (1 << 10) /* 1 KBytes (512 + 512 ^^) */

int main(int s_Argc, char **s_Argv)

{

const char *s_ProcStat = “/proc/stat”;

const char *s_CPUName = “cpu “;

int s_Handle, s_Check, s_Count;

char s_StatBuffer[ DEF_PROCSTAT_BUFFER_SIZE ];

char *s_String;

unsigned long s_CPUTick[2][5];

float s_DiffTotal;

fprintf(stdout, “MZ_cpuusage v1.0.0 – Copyright(c)InfoEQ co.,LTD – %s %s\\n”, __DATE__, __TIME__);

fprintf(stdout, “Code by JaeHyuk Cho – < minzkn@infoeq.co.kr >\\n\\n”);

memset(&s_CPUTick[0][0], 0, sizeof(s_CPUTick));

do

{

s_Handle = open(s_ProcStat, O_RDONLY);

if(s_Handle >= 0)

{

s_Check = read(s_Handle, &s_StatBuffer[0], sizeof(s_StatBuffer) – 1);

close(s_Handle);

if(s_Check > 0)

{

s_StatBuffer[s_Check] = ‘\\0’;

s_String = strstr(&s_StatBuffer[0], s_CPUName); /* Total CPU entry */

if(s_String)

{

s_Check = sscanf(s_String, “cpu %lu %lu %lu %lu”, \\

&s_CPUTick[0][0], &s_CPUTick[0][1], &s_CPUTick[0][2], &s_CPUTick[0][3]);

if(s_Check == 4)

{

for(s_Count = 0, s_CPUTick[0][4] = 0lu; s_Count < 4;s_Count++)s_CPUTick[0][4] += s_CPUTick[0][s_Count];

s_DiffTotal = (float)(s_CPUTick[0][4] – s_CPUTick[1][4]);

if(s_DiffTotal > 0.0)

{

fprintf(stdout, “[CPU] User=%1.2f%%, Nice=%1.2f%%, System=%1.2f%%, Idle=%1.2f%%\\n”, \\

(float)( (float)((s_CPUTick[0][0] – s_CPUTick[1][0]) * 100lu) / s_DiffTotal ),\\

(float)( (float)((s_CPUTick[0][1] – s_CPUTick[1][1]) * 100lu) / s_DiffTotal ),\\

(float)( (float)((s_CPUTick[0][2] – s_CPUTick[1][2]) * 100lu) / s_DiffTotal ),\\

(float)( (float)((s_CPUTick[0][3] – s_CPUTick[1][3]) * 100lu) / s_DiffTotal ));

memcpy(&s_CPUTick[1][0], &s_CPUTick[0][0], sizeof(s_CPUTick) >> 1);

}

else fprintf(stderr, “%s: Destroy proc fs !!!\\n”, s_Argv[0]);

}

else fprintf(stderr, “%s: Can not parse !!!\\n”, s_Argv[0]);

}

else fprintf(stderr, “%s: Can not found info !!!\\n”, s_Argv[0]);

}

else fprintf(stderr, “%s: Can not read %s !!!\\n”, s_Argv[0], s_ProcStat);

}

else fprintf(stderr, “%s: Can not open %s !!!\\n”, s_Argv[0], s_ProcStat);

sleep(1); /* Check term */

}while(1);

return(0);

}

/* End of source */

====================== [ 절취선 ] ============================

서진우

슈퍼컴퓨팅 전문 기업 클루닉스/ 상무(기술이사)/ 정보시스템감리사/ 시스존 블로그 운영자

You may also like...

페이스북/트위트/구글 계정으로 댓글 가능합니다.