libcurl in multithreads

来源:互联网 发布:单管共射放大电路数据 编辑:程序博客网 时间:2024/05/19 17:56
libcurl在多线程中使用时,需要设置CURLOPT_NOSIGNAL为1,否则会引起程序crash。 但是设置了CURLOPT_NOSIGNAL之后,在域名dns解析时,设置的超时就不起作用,这样容易引起整个任务超时。此时,解决此问题,使超时设置生效的方法是:重新编译libcurl,使c-ares生效(异步解析dns),具体方法如下:1. 安装c-ares:   yum install c-ares-devel2.编译libcurl:wget http://curl.haxx.se/download/curl-7.40.0.tar.gztar zxvf curl-7.40.0.tar.gz cd curl-7.40.0/./configure --enable-ares --prefix=/usr/local/curl --with-sslmake && 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);