Skip to content

Libcurl

cURL의 C API와 관련된 내용 정리.

에러메시지 Catch

C 소스내에서 popen()을 호출하여 실행할 경우, 다음과 같이 Redirect 문자를 추가하여, 에러메시지를 catch할 수 있다.

snprintf(cmd, sizeof(cmd), "curl -T \"%s\" -u \"%s:%s\" ftp://%s:%d/%s/ -s -S -m %d --connect-timeout %d --ftp-create-dirs 2>&1",
        src_file, userid, passwd,
        ipaddr, port, dst_dir,
        timeout, conn_timeout);

fp = popen(cmd, "r");
if(fp == NULL) {
    LOG_ERR("%s:: popen() fail: errno=%d(%s)\n",
            _func_, errno, strerror(errno));
    return -1;
}
while(fgets(buff, sizeof(buff), fp) != NULL) {
    LOG_ERR("%s:: ftp upload error: err=%s", _func_, buff);
    success_flag = 0;
    break;
}
pclose(fp);

Thread safety

/* This is the callback executed when a new threads starts */
static void *pull_one_url(void *url)
{
  CURL *curl;

  curl = curl_easy_init();
  curl_easy_setopt(curl, CURLOPT_URL, url);
  curl_easy_perform(curl); /* ignores error */ 
  curl_easy_cleanup(curl);

  return NULL;
}

/* ... */

/* This is the main loop that creates `NUMT` threads for parallel fetching */
for(i=0; i< NUMT; i++) {
    error = pthread_create(&tid[i],
                           NULL, /* default attributes please */ 
                           pull_one_url,
                           (void *)urls[i]);
  /* ... */
}

FTP 사이트 검색

FTP 사이트에서 특정 문자열(or 정규표현식)에 맞는 파일명을 찾아내는 기능.

사용방법

curl_ftpdir [-s "string or expression"] [-u userid:password] [-a] [-l] [-g] <FTP URL>

유닉스 표준 명령행 문법에 따라서 [] 괄호는 Optional field이고, <>나 무괄호는 Required field입니다. 즉 최소한으로 FTP URL만 입력되어도 작동은 합니다.

-s "string or expression"
해당 FTP URL주소 아래에서 검색할 정확한 파일명이나 정규표현식을 사용합니다. 정규표현식은 POSIX 표준 형식을 지원합니다.
-u userid:password
FTP 사이트에 접속할 때 사용할 유저명과 패스워드로서 콜론을 구분자로 사용하여 userid:password의 형식으로 입력합니다.
이 옵션을 사용하지 않으면 Anonymous(익명FTP)로 접속합니다.
-a
매칭된 파일만을 출력합니다. 기본적으로 이 유틸리티는 FTP URL의 모든 파일명을 보여주고, 구분하기 위해 매치된 파일명만 밝게 Yellow색상으로 표시합니다. 그러나 이 옵션이 사용되면 검색옵션(-s ...)에 매치된 파일명만 보여주고, 매치되지 않은 나머지 파일은 표시하지 않습니다.
-l
하이라이트 기능을 끕니다. 이 기능은 ANSI 컬러를 이용하여 출력하는 것을 사용하지 않습니다.
-g
디버깅 기능을 사용합니다. 작동하는 동안의 FTP 명령어들이 어떻게 작동되는지 보여주고, 마지막에 검색한 URL의 하위 디렉토리 리스트도 보여줍니다.

See also

Favorite site

How to build libcurl