libcurl in multithreads

libcurl在多线程中使用时,需要设置CURLOPT_NOSIGNAL为1,否则会引起程序crash。 但是设置了CURLOPT_NOSIGNAL之后,在域名dns解析时,设置的超时就不起作用,这样容易引起整个任务超时。
此时,解决此问题,使超时设置生效的方法是:重新编译libcurl,使c-ares生效(异步解析dns),具体方法如下:
1. 安装c-ares:
   yum install c-ares-devel
2.编译libcurl:
wget http://curl.haxx.se/download/curl-7.40.0.tar.gz
tar zxvf curl-7.40.0.tar.gz 
cd curl-7.40.0/
./configure --enable-ares --prefix=/usr/local/curl --with-ssl
make && make install

编译过程中,可能会出现~/lib/version.c 110: implicit declaration of 'ares_version', 只需要在头文件包含:#include<ares_version.h> 就可以解决。

编译完成之后,应用程序重新编译即可。此时域名解析就不会卡住。具体使用实例如下:

    CURL* curl;
    CURLcode res;
    long resp_code;

    curl = curl_easy_init();
    if (!curl) {
        return -1;
    }

    curl_easy_setopt(curl, CURLOPT_URL, url);

    if (method == HTTP_METHOD_POST)
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, size);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 2L);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5L);

    /*When using multiple threads you should set the CURLOPT_NOSIGNAL(3)
    option to 1 for all handles. Everything will or might work fine except that
    timeouts are not honored during the DNS lookup- which you can work around by
    building libcurl with c-ares support. c-ares is a library that provides
    asynchronous name resolves.*/
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
    curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 1L);

    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        curl_easy_cleanup(curl);
        return -1;
    }

    /*must use parameter witch type long to get response code, otherwise will cause stack problem*/
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &resp_code);
    *http_code = resp_code;

    curl_easy_cleanup(curl);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值