'Linux/Linux:c개발'에 해당되는 글 8건

  1. 2015.10.08 Valgrind, CppCheck, gCoverage, gProfiler
  2. 2015.04.17 va_list 가변파라미터
  3. 2015.04.14 pthread
  4. 2015.04.14 gethostbyname
  5. 2015.04.13 c에서 c++파일 하나 불러쓰기
  6. 2015.03.27 Shared Memory
  7. 2014.09.16 c개발 : 실행시간 측정.
  8. 2014.09.16 c 개발: shared library 경로 설정

linux에서 c로 개발한 후, 코드를 검사하는 방법 몇가지.. 

 

 

ValgrindREF-SITE

 - 메모리 오류 체크, 메모리 leak 체크.

   특히 메모리 오류가 가장 짜증나는 부분인데 이런 부분을 제법 잡아주므로 꼭 돌릴 필요가 있다.

 

- 사용법:

$gcc test.c -o app_test

$valgrind --leak-check=yes ./app_test

    

 

CppCheck   http://cppcheck.sourceforge.net/

-  Linux버전도 있고, pc버전도 있으며, 파일 단위나 폴더단위로 소스를 검사.

   메모리 누수/배열 범위/멀티 Thread 등이 check됨.

 

 

 

gcov REF-SITE

- 사용(혹은 TEST) 이 안되고 있는 코드 체크, 코드별 실행 횟수 및 %가 나온다.

 

- 사용법:

  $gcc -fprofile-arcs -ftest-coverage tmp.c
  $./a.out
  $gcov tmp.c

 

 

gprof

- 코드 성능 분석

Posted by yongary
,

가변 파라미터를 받아서 사용하는 방법: (vprintf로 출력가능 한데)

=> 약간 변조하고 싶을 때에는 vsprintf를 사용하면 된다... 



#include <stdarg.h>


void logPRINTD(const char* format, ...){ 

    char str[512];

    

va_list args;

    va_start(args, format);

    vsprintf(str, format, args);  //str로 옮기기

    strcat(str,"\n"); /////////////////////  str에 \n 더하기

    va_end(args); 


//str로 하고싶은일 하기. bla bla 

}   


Posted by yongary
,

pthread

Linux/Linux:c개발 2015. 4. 14. 11:28

참조: http://www.joinc.co.kr/modules/moniwiki/wiki.php/Site/Thread/Beginning/PthreadApiReference 



Thread의 상태:

PTHREAD_CREATE_JOINABLE  : 다른 thread끝나고 동작하는 thread. (exit나 join을 호출을 통해서 자원을 반납해야 하는 thread.)

PTHREAD_CREATE_DETACHED : 독립적으로 동작하므로 종료시점 체크필요없고, 종료시 자동자원반납. 



<구조체>


typedef  long pthread_t;

struct pthread_attr {
  void *stackaddr;
  size_t stacksize;
  int detachstate;
  struct sched_param param;
  int inheritsched;
  int contentionscope;
};

typedef struct pthread_attr pthread_attr_t;
#define PTHREAD_CREATE_JOINABLE       0
#define PTHREAD_CREATE_DETACHED       1


<예제 - 심플 detatched thread 생성. >

 pthread_t id;

 pthread_attr_t attributes;  



// initialize thread attributes

    pthread_attr_init(&attributes)

    pthread_attr_setdetachstate( &attributes, PTHREAD_CREATE_DETACHED);


//create a new thread 

   pthread_create( &myId, &attributes, startFunc, args);  //args는 startFunc로 전달. 

   pthread_attr_destroy(&attributes); //자원해제 



Posted by yongary
,

gethostbyname

Linux/Linux:c개발 2015. 4. 14. 09:46

<함수 prototype>

struct hostent *gethostbyname(const char *name);

int gethostbyname_r(const char *name,
               struct hostent *ret, char *buf, size_t buflen,
               struct hostent **result, int *h_errnop);


두 함수 모두 return type은 hostent  struct 이다.


<struct hostent 구조 >

struct hostent { char *h_name; /* official name of host */ char **h_aliases; /* alias list */ int h_addrtype; /* host address type */ int h_length; /* length of address */ char **h_addr_list; /* list of addresses */ 

==> 아래쪽에 in_addr구조체의 s_addr 변수 참조. 같은 형태임. 0xff01ffff의 네트웍바이트(순서대로) 형태(255.1.255.255)

} #define h_addr h_addr_list[0] /* for backward compatibility */ The members of the hostent structure are:


h_addrtype The type of address; always AF_INET or AF_INET6 at present. h_length The length of the address in bytes. h_addr_list An array of pointers to network addresses for the host (in net- HOST_NOT_FOUND The specified host is unknown. NO_ADDRESS or NO_DATA The requested name is valid but does not have an IP address. NO_RECOVERY A non-recoverable name server error occurred. TRY_AGAIN A temporary error occurred on an authoritative name server. Try again later.



<그 외 network관련 struct들 >

           struct sockaddr_in {
               sa_family_t    sin_family; /* address family: AF_INET */
               in_port_t      sin_port;   /* port in network byte order */
               struct in_addr sin_addr;   /* internet address */
           };

           /* Internet address. */
           struct in_addr {
               uint32_t       s_addr;     /* address in network byte order */  
           };

0xffffffff의 네트웍바이트 형태.=255.255.255.255


<in_addr_t  inet_addr(hostname) 함수> 이름을 0xffffffff (255.255.255.255 효과) 형태로 변환리턴.


리턴type:  typedef uint32_t in_addr_t;   

INADDR_NONE= -1 (255.255.255.255)을 리턴하는 경우. 약간문제가 될때도 있으나 거의 괜찮음.




Posted by yongary
,

c++하나를 불러쓰는 경우

 

wrapping layer를 만들어서,

c언어에서 불러쓰면 된다.

 

예) c++파일 안에서

 

extern "C" {

MyClass* myclass_new()

{

return new MyClass();

}

..몇개 함수 더 매핑.

}

이렇게만 하면,

main. c파일안에서 아래와 같이 호출이 가능하다.

 

struct MyClass *m = myclass_new();

 

 

 

그리고  build시에는 특히 c빌드시(혹은 최종 link시에)

gcc main.c -lstdc++  추가 필요....

 

 

 

참고 blog: http://ospace.tistory.com/215 

Posted by yongary
,

Shared Memory

Linux/Linux:c개발 2015. 3. 27. 15:33

Linux  c개발시  shm 사용방법.


  shmget  : malloc 처럼 공유메모리 생성


  shmat   : 생성된 공유메모리를 해당 프로세서로 가져옴(첨부-attach)


  shmdt    :  가져온 메모리를 다시 반납. (분리-detach )


  



Posted by yongary
,

< 함수의 실행시간을 milisecond단위로 측정하는 방법. > 



struct timeval을 이용하여 함수의 실행시간을 측정하는 방법인데,


 struct timeval은 초와 micro초로 이루어져 있으므로,

- 초에는 *1000을 

 - micro초에는 /1000 을 해야 milisecond가 된다.


struct timeval { long tv_sec; // 초 long tv_usec; // micro }



=======사용예제================================================

#include <sys/time.h>


struct timeval before,after;  //선언


//사용 
    gettimeofday(&before,NULL);
    run_my_function( );
    gettimeofday(&after,NULL);

    printf("function running time[ms] : %ld\n",
         1000*(after.tv_sec-before.tv_sec) +   
         (after.tv_usec-before.tv_usec)/1000);





Posted by yongary
,


Linux에서 c언어 개발 중,


make는 완료 했으나

실행 중에 .so(공유 library)를 못 찾는 경우 다음과 같이 해결하면 된다.

(이 때, 에러메시지:  cannot open shared object file - no such file or directory)



(UBUNTU)

1. /etc/ld.so.conf.d/  밑에  myApp.conf 파일 추가

2. myApp.conf 파일 첫 줄에

  /usr/lib/myApp/lib  과 같이 특정한 위치 지정    

3. sudo ldconfig (Reload임)



(Debian)

1. /etc/ld.so.conf 편집

2. 마지막 줄에 /usr/lib/myApp/lib 과 같은 특정한 위치 추가

3. ldconfig (Reload임)    (조회는 ldconfig -v)



참조: http://blog.andrewbeacock.com/2007/10/how-to-add-shared-libraries-to-linuxs.html 



또다른 간단한 방법으로는

run 쉘스크립트를 하나 만드는 것이다.


#!/bin/bash

LD_LIBRARY_PATH=/home/myid/common/lib:$LD_LIBRARY_PATH

export LD_LIBRARY_PATH

./test_program

Posted by yongary
,