strace로 프로세스 상태를 체크하다가 보게 되었습니다.


FUTEX 란?

   출처 : http://www.hanbit.co.kr/preview/1492/sample_chap01.pdf

리눅스 커널 2.6에는 새로운 프로세스 간의 통신으로 FUTEX라는 것이 있습니다. 이것은 동일 머신 상의 복수 프로세스 간에 잠금(Lock) 처리를 합니다. 동일 페이지를 프로세스에 매핑하고, 그 위에 잠금 변수를 공유하게 함으로써 경합이 발생하지 않는 한 시스템 콜 개입 없이 잠금 처리를 할 수 있습니다. 많은 프로 세스나 스레드가 협조하여 동작하는 응용 프로그램에서는 매우 유용한 구조입니다.


FUTEX_WAIT ?

                           출처 : https://meenakshi02.wordpress.com/2011/02/02/strace-hanging-at-futex/

FUTEX_WAIT의 의미 

which simply means you are tracing the original parent thread, 

and it’s doing nothing but waiting for some other threads to finish.


[root@upi1 bin]# strace -p 24866
Process 24866 attached – interrupt to quit
futex(0xa280a0c, FUTEX_WAIT, 1, NULL



FUTEX_WAIT 과 FUTEX_WAIT_PRIVATE 차이 ?

출처: http://stackoverflow.com/questions/9983765/what-is-the-difference-between-futex-wait-and-futex-wait-private

This is an optimization done by linux/glibc to make futexes faster when they're not shared between processes. Glibc will use the _PRIVATE versions of each of the futex calls unless the PTHREAD_PROCESS_SHARED attribute is set on your mutex



데모 소스코드


#define _GNU_SOURCE

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <linux/futex.h>
#include <sys/time.h>

#define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
} while (0)

static int *futex1, *futex2, *iaddr;

static int futex(int *uaddr, int futex_op, int val,
        const struct timespec *timeout, int *uaddr2, int val3)
{
    return syscall(SYS_futex, uaddr, futex_op, val,
            timeout, uaddr, val3);
}

#define _GNU_SOURCE
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
} while (0)

static int *futex1, *futex2, *iaddr;

static int futex(int *uaddr, int futex_op, int val,
        const struct timespec *timeout, int *uaddr2, int val3)
{
    return syscall(SYS_futex, uaddr, futex_op, val,
            timeout, uaddr, val3);
}

/* Acquire the futex pointed to by 'futexp': wait for its value to
   become 1, and then set the value to 0. */

static void fwait(int *futexp)
{
    int s;

    /* __sync_bool_compare_and_swap(ptr, oldval, newval) is a gcc
       built-in function.  It atomically performs the equivalent of:

       if (*ptr == oldval)
     *ptr = newval;

     It returns true if the test yielded true and *ptr was updated.
     The alternative here would be to employ the equivalent atomic
     machine-language instructions.  For further information, see
     the GCC Manual. */

    while (1) {

        /* Is the futex available? */

        if (__sync_bool_compare_and_swap(futexp, 1, 0))
            break;      /* Yes */

        /* Futex is not available; wait */

        s = futex(futexp, FUTEX_WAIT, 0, NULL, NULL, 0);
        if (s == -1 && errno != EAGAIN)
            errExit("futex-FUTEX_WAIT");
    }
}

/* Release the futex pointed to by 'futexp': if the futex currently
   has the value 0, set its value to 1 and the wake any futex waiters,
   so that if the peer is blocked in fpost(), it can proceed. */

static void fpost(int *futexp)
{
    int s;

    /* __sync_bool_compare_and_swap() was described in comments above */

    if (__sync_bool_compare_and_swap(futexp, 0, 1)) {

        s = futex(futexp, FUTEX_WAKE, 1, NULL, NULL, 0);
        if (s  == -1)
            errExit("futex-FUTEX_WAKE");
    }
}

int main(int argc, char *argv[])
{
    pid_t childPid;
    int j, nloops;

    setbuf(stdout, NULL);

    nloops = (argc > 1) ? atoi(argv[1]) : 5;

    /* Create a shared anonymous mapping that will hold the futexes.
       Since the futexes are being shared between processes, we
       subsequently use the "shared" futex operations (i.e., not the
       ones suffixed "_PRIVATE") */

    iaddr = mmap(NULL, sizeof(int) * 2, PROT_READ | PROT_WRITE,
            MAP_ANONYMOUS | MAP_SHARED, -1, 0);
    if (iaddr == MAP_FAILED)
        errExit("mmap");

    futex1 = &iaddr[0];
    futex2 = &iaddr[1];

    *futex1 = 0;        /* State: unavailable */
    *futex2 = 1;        /* State: available */

    /* Create a child process that inherits the shared anonymous
       mapping */

    childPid = fork();
    if (childPid == -1)
        errExit("fork");

    if (childPid == 0) {        /* Child */
        for (j = 0; j < nloops; j++) {
            fwait(futex1);
            printf("Child  (%ld) %d\n", (long) getpid(), j);
            fpost(futex2);
        }

        exit(EXIT_SUCCESS);
    }

    /* Parent falls through to here */

    for (j = 0; j < nloops; j++) {
        fwait(futex2);
        printf("Parent (%ld) %d\n", (long) getpid(), j);
        fpost(futex1);
    }

    wait(NULL);

    exit(EXIT_SUCCESS);
}







반응형

error: use of assignment suppression and length modifier together in gnu_scanf format


--> 컴파일 정상

+     fscanf(fp, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %*u %*d %*d %*d %*d %*d %*d %llu ", &starttime);

---

---> 컴파일 경고

-      fscanf(fp, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*lu %*lu %*d %*d %*d %*d %*d %*d %llu ", &starttime);



gnu_scanf format을 따르려면 *을 사용할때 long 타입은 빼줘야 됐습니다.

정확한 format은 아직 안 찾아봤습니다.

반응형

'Language > C' 카테고리의 다른 글

futex 함수 (Fast User muTEX)  (5) 2016.02.04
MYSQL 쿼리 모음  (5) 2014.07.02
각 변수별 min, max  (6) 2014.01.13
C언어 추천도서 (초급, 중급, 고급)  (6) 2013.06.21
파일사이즈구하기 예제 (c언어 linux)  (6) 2013.06.18

DB를 써보지도 않다가 개발을 하게 되어.. 

이곳에 정리해두고 한번에 보기 위해 작성합니다.


1. ROW 개수 구하기

 > SELECT COUNT(*) FROM TABLE


2. 삭제

 > DELETE FROM TABLE;


3. 동일한 ROW가 반복될 때 하나만 대표적으로 가져오기

 > SELECT system FROM TABLE WHERE group='TEST' GROUP BY system;


4. 특정 조건인 ROW를 제외하고 값을 가져오기

 > SELECT MAX(status) FROM TABLE WHERE group='TEST' AND on_off NOT LIKE 1;


5. 정렬해서 보기

 > SELECT * FROM TABLE WHERE system='TEST_SYSTEM' ORDER BY col1, col2, col3;


6. 여러개의 ROW 한번에 삽입 (INSERT MULTI-ROW)

 > INSERT INTO SYSTEM VALUES ('A1', 'B1', 'C1'), ('A2', 'B2', 'C2');




반응형

출처 : http://mwultong.blogspot.com/2006/09/c-char-int-float-data-type-ranges.html

개인적으로 그때그때 보려고 퍼왔습니다..



▶ char, unsigned char          1 byte (8비트)

------------------------------------------------------

char 의 최소값: -128

char 의 최대값: 127


unsigned char 의 최소값: 0

unsigned char 의 최대값: 255 (0xff)




▶ short, unsigned short        2 bytes (16비트)

------------------------------------------------------

short 의 최소값: -32768

short 의 최대값: 32767


unsigned short 의 최소값: 0

unsigned short 의 최대값: 65535 (0xffff)



▶ wchar_t 또는 __wchar_t       2 bytes (16비트)

------------------------------------------------------

wchar_t 의 최소값: 0

wchar_t 의 최대값: 65535


※ wchar_t 는 유니코드 글자 1개를 저장합니다. "unsigned short"과 동일.




▶ int, unsigned int            4 bytes (32비트)

------------------------------------------------------

int 의 최소값: -2147483648

int 의 최대값: 2147483647


unsigned int의 최소값: 0

unsigned int의 최대값: 4294967295 (0xffffffff)




▶ long, unsigned long          4 bytes (32비트)

------------------------------------------------------

long 의 최소값: -2147483648L

long 의 최대값: 2147483647L


unsigned long 의 최소값: 0UL

unsigned long 의 최대값: 4294967295UL (0xffffffffUL)


※ 32비트OS에서의 long 은 int 와 동일




▶__int64 또는 long long        8 bytes (64비트)

------------------------------------------------------

__int64 의 최소값: -9223372036854775808i64

__int64 의 최대값: 9223372036854775807i64


unsigned __int64 의 최소값: 0ui64

unsigned __int64 의 최대값: 18446744073709551615ui64 (0xffffffffffffffffui64)






실수 자료형


▶ float                        4 bytes (32비트)

------------------------------------------------------

가장 작은 양수: 1.175494351e-38F

가장 큰 양수  : 3.402823466e+38F




▶ double                       8 bytes (64비트)

------------------------------------------------------

가장 작은 양수: 2.2250738585072014e-308

가장 큰 양수  : 1.7976931348623158e+308




▶ long double                  8 bytes (64비트)

------------------------------------------------------

double 과 같음.

반응형

C언어로 일한지 2년이 넘어가니 조금 익숙해져가는데, 

보다더 자세히 알아보고 싶은 와중에 

좋은 정보가 있어서 여기에 올려두고 공유하려합니다.

http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list



참조해야할 레퍼런스, 초급, 중급, 고급에 따라서 볼만한 책들인데.

괜히 고급단계에 있는 책은 꼭 한번 봐야할 것 같은 기분은 왜인지....

  - 고급레벨의 'expert c programming deep c secrets' 책은 PDF로 받아 볼수도 있습니다. 

http://www.e-reading-lib.org/bookreader.php/138815/Linden_-_Expert_C_Programming%3A_Deep_C_Secrets.pdf


Reference Style - All Levels

  1. The C Programming Language (Second edition) - Brian W. Kernighan and Dennis M. Ritchie
  2. C: A Reference Manual - Samuel P. Harbison and Guy R. Steele
  3. C Pocket Reference (O'Reilly) - Peter Prinz, Ulla Kirch-Prinz

Beginner

  1. Programming in C (3rd Edition) - Stephen Kochan
  2. C Primer Plus - Stephen Prata
  3. C Programming: A Modern Approach - K. N. King
  4. A Book on C - Al Kelley/Ira Pohl
  5. Learn C The Hard Way - Zed Shaw
  6. The C book - Mike Banahan, Declan Brady and Mark Doran
  7. Practical C Programming, 3rd Edition - Steve Oualline
  8. C: How to Program (6th Edition) - Paul Deitel & Harvey M. Deitel
  9. Head First C - David & Dawn Griffiths

Intermediate

  1. 21st Century C - Ben Klemens
  2. Object-oriented Programming with ANSI-C - Axel-Tobias Schreiner
  3. C Interfaces and Implementations - David R. Hanson
  4. The C Puzzle Book - Alan R. Feuer
  5. The Standard C Library - P.J. Plauger

Above Intermediate

  1. Expert C Programming: Deep C Secrets - Peter van der Linden


반응형

'Language > C' 카테고리의 다른 글

MYSQL 쿼리 모음  (5) 2014.07.02
각 변수별 min, max  (6) 2014.01.13
파일사이즈구하기 예제 (c언어 linux)  (6) 2013.06.18
extern 선언에 대한 쉬운설명  (6) 2012.12.07
fwrite함수 예제  (6) 2012.11.06

파일의 크기를 구하기 위해서 stat 함수를 이용해서

구현이 가능



---

#include 
#include 
#include 
#include 
#include "sys/stat.h"

static size_t get_file_size (const char * file_name)
{
    struct stat sb;
    if (stat (file_name, & sb) != 0) {
        fprintf (stderr, "'stat' failed for '%s': %s.\n",
                file_name, strerror (errno));
        exit (EXIT_FAILURE);
    }
    return sb.st_size;
}

int main (int argc, char ** argv)
{
    int i;
    const char * file_name;
    size_t size;

    file_name = argv[1];
    size = get_file_size (file_name);
    printf ("%20s has %d bytes.\n", file_name, size);
    return 0;
}
--------------------------------------
[결과 화면]
$ ./a.out temp_err_code
       temp_err_code has 15096 bytes.
--------------------------------------

---

반응형

'Language > C' 카테고리의 다른 글

각 변수별 min, max  (6) 2014.01.13
C언어 추천도서 (초급, 중급, 고급)  (6) 2013.06.21
extern 선언에 대한 쉬운설명  (6) 2012.12.07
fwrite함수 예제  (6) 2012.11.06
switch case문과 if문의 성능차이  (8) 2012.10.31

전역변수로 선언한 것을 다른 파일에서 선언하여

사용할 때, 쓴다라고 정도로만 알고 있었는데 


http://tksssch29.tistory.com/162 에서 참조함



extern는 다른 파일에 선언되어 있는 전역변수에 대한 링크 시킨다는 의미이다.

extern 변수 선언시 변수의 타입을 기입하지 않는 경우가 있는데 이때 컴파일러는 type checjing작업을 통해
묵시적으로 사용된 값에 대한 타입을 예상하게 된다. 이는 곧 타입에 대한 기재가 없어도 심볼테이블을 통해
변수의 타입을 알아낸다는 의미가 되겠다.
하지만 만일 묵시적으로 선언된 변수가 외부에서 두가지 이상의 타입으로 선언되어 있다면 컴파일러가
어느 타입인지 추론하는게 어렵기 때문에 Link시 에러가 날 가능성이 있는 것이다.

많은 사람들이 extern 키워드를 이용하면 따로 변수를 선언하여 메모리를 잡는다고 이해하는 사람이 많다.
extern 키워드는 다른 파일에 선언되어 있는 변수를 링크시켜 자신이 만들고자 하는 프로그램에 쓸 수 있는 것이라
생각하면 된다. extern 키워드는 컴파일러에게 

"이러한 변수가 어딘가에 선언되어 있고 그거 쓸꺼니까 메모리 올리지 말고 일단 그냥 넘어가~"
라는 말을 하는 것이다.

extern로 선언된 변수는 Link시에 심볼테이블을 검색을 통해 다른 obj들로 부터 찾게 된다. 

다시 정리 하자!
extern 키워드를 사용해서 변수를 명시했다고 그것이 변수 선언을 의미하는게 아니다. 즉 메모리를 잡지 않는다는 것이다. 그 변수에 대한메모리는 다른 파일?에서 잡혀 있을거고, 링크타임때 그 변수에 대한 메모리를 찾아 링크시키는 것이다.

반응형

fwirte 함수를 가지고 바이너리 파일 쓰기를 하는데 

2,3번째 인자가 해깔린다... ㅜ.ㅜ


ptr

스트림에 쓰여질 배열을 가리키는 포인터.


size

그 배열의 각각의 원소의 크기

count

그 배열의 원소의 수 이다. 이 때, 각 원소의 크기는 size 바이트 이다.

stream

내용을 쓸 스트림을 가리키는 FILE 포인터

출처 :: http://itguru.tistory.com/69

--

#include 

int main ()
{
  FILE * pFile;
  char buffer[] = { 'x' , 'y' , 'z' };
  pFile = fopen ( "myfile.bin" , "wb" );
  fwrite (buffer , 1 , sizeof(buffer) , pFile );
  fclose (pFile);
  return 0;
}

---- 기타 fwrite example ----
FILE *fp;
fp=fopen("c:\\test.bin", "wb");
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
----------------------------





--

반응형

+ Recent posts