[C프로그래밍] 소스 해석- 도와 주세요. 마땅한 주제가 없네요 &

uamyd5279의 이미지

먼저 앞쪽은 메인 함수 중에 일부입니다. 이해하기 쉽도록,,혹시 모를 에러를 대비해서 올렸습니다. 참고 부분..

FILE *fp;
char tempbuf[1024]'
static long     cpustate[4], oldstate[4], newstate[4], diffstate[4];

fp=fopen("/proc/stat","r");
fgets(tempbuf, 1023, fp);

fclose(fp);

sscanf( tempbuf, "%s %lu %lu %lu %lu", path, &newstate[0], &newstate[1], &newstate[2], &newstate[3] );
percentages( 4, cpustate, newstate, oldstate, diffstate );

해석을 원하는 함수 입니다. 앞에서 본 마지막 줄의 percentage함수의 소스입니다.
long percentages(int cnt, long *out, register long *new, register long *old, long *diffs)
{
    register int i;
    register long change;
    register long total_change;
    register long *dp;
    long half_total;

    /* initialization */
    total_change = 0;
    dp = diffs;

    /* calculate changes for each state and the overall change */
    for( i = 0; i < cnt; i++)
    {
        if ((change = *new - *old) < 0)
        {
                /* this only happens when the counter wraps */
                change = (int) ((unsigned long)*new-(unsigned long)*old);
        }
        total_change += (*dp++ = change);
        *old++ = *new++;
    }

    /* avoid divide by zero potential */
    if( total_change == 0)
    {
        total_change = 1;
    }

    /* calculate percentages based on overall change, rounding up */
    half_total = total_change / 2l;
    for(i = 0; i < cnt; i++)
    {
        *out++ = (int)((*diffs++ * 1000 + half_total) / total_change);
    }

    /* return the total in case the caller wants to use it */
    return(total_change);
}

기초가 다져지신 분들은 아시겠지만, '/proc/stat'에는 여러가지 시스템 정보가 들어 있는데, 그 중에 첫 줄에는 전체 CPU의 jiffie값이 들어 있죠. 순서대로, 'user, systme, nice, idle '...

이 함수는 전체 CPU사용량- jiffies의 변화-를 체크해서 퍼센티지로- 좀 더 정확히 말씀드리면 100퍼센트가 아니라 1000퍼센트죠..- 환산해서 사용자에게 보기 좋게 해주는 데 사용이 됩니다.

그런데, 정확하게 이해가 되지않네요.

특히 이 부분!!

half_total = total_change / 2l;
    for(i = 0; i < cnt; i++)
    {
        *out++ = (int)((*diffs++ * 1000 + half_total) / total_change);
    }

맨 첫줄 끝에는 2하고 영어 L 의 소문자가 붙어 있는데요...
창피한 일이겠지만, 정말 저게 뭘 의미하는지 모르겠어요.

결과로는 out쪽에 퍼센티지로 환산한 값을 넘겨 주게 되는데요.
바로 위의 소스의 계산을 살펴보면...
각 필드별(user, nice,system, idle) 차이 값을 각각 a, b, c, d라고 했을 때

'out(a의 퍼센티지값) = ((a곱하기 1000)+((a+b+c+d)/2l)) / (a+b+c+d)'

이렇게 볼 수 있는데 쉽게 말해서..
' out (a의 퍼센티지값) = 1/2l + a의 천분율'
아닌가요?

제가 정말 궁금한건 2가지 입니다.
소스에서 사용된 '2l'의 의미 또는, '1/2l'을 더하는 것은 무슨 의미가 있는가 하는 것과,

저 메인 쪽에 보시면, 자세히 적진 않았지만, 초기값이 없습니다!!
최초 값이 없다는 말이죠.

어떻게 값이 나오는지 그 원리,가 궁금합니다.

혹시 아시는 분..계시다면.....부탁드립니다.
도와 주세요.

chadr의 이미지

기본적으로 숫자 상수는 int형입니다..

그걸 long형으로 변환하고 싶으면 숫자 뒤에다가 l 을 붙이면 됩니다..

2l 은 숫자 2이 long형이다. 라고 컴파일러에게 알려주는 것입니다.

-------------------------------------------------------------------------------
It's better to appear stupid and ask question than to be silent and remain stupid.

mach의 이미지

Quote:
..............
10진상수: O이외의 숫자로 시작하는 수치를 말한다.
예) 123, -123, +123
8진 상수: O으로 시작하는 수치를 말한다. (0은 zero를 의미)
예) O17, O12
16진 상수: Ox로 시작하는 수치를 말한다.
예) OxAB, Ox123
long 상수: 상수 끝에 L을 붙인 수치로 10진, 8진, 16진 상수에 지정한다.
예) 123L, OxAB3CL
......

------------------ P.S. --------------
지식은 오픈해서 검증받아야 산지식이된다고 동네 아저씨가 그러더라.

k2hyun의 이미지

*out++ 을 말씀하시는건가요?

함수 호출할때 out 으로 넘겨주는 인자는 아마도 long 배열의 첫번째 주소일테고요.

:wink:

더 이상 없다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.