【问题标题】:Curl causes openssl error卷曲导致openssl错误
【发布时间】:2015-05-31 13:42:10
【问题描述】:

我当前的 curl 设置调用网页,将其保存为字符串,并在休眠一秒钟后重复该过程。这是写入字符串的代码:

#include <curl/curl.h>
#include <string>
#include <iostream>
#include <thread>
#include <chrono>

size_t curl_writefunc(void* ptr, size_t size, size_t nmemb, std::string* data)
{
    data->append((const char*)ptr, size * nmemb);
    return size * nmemb;
}

void curl_handler(std::string& data)
{
    int http_code = 0;
    CURL* curl;
    // Initialize cURL
    curl = curl_easy_init();

    // Set the function to call when there is new data
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_writefunc);

    // Set the parameter to append the new data to
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);

    // Set the URL to download; just for this question.
    curl_easy_setopt(curl, CURLOPT_URL, "http://www.example.com/");

    // Download
    curl_easy_perform(curl);

    // Get the HTTP response code
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);

    // Clean up
    curl_easy_cleanup(curl);
    curl_global_cleanup();
}

int main()
{
    bool something = true;
    std::string data;
    while (something)
    {
        curl_handler(data); 
        std::cout << data << '\n';
        data.clear();
        std:: this_thread:: sleep_for (std:: chrono:: seconds(1));
    }
}

然而,它在运行大约 20 分钟后遇到了问题,这是它面对我的消息:

140377776379824:error:02001018:system library:fopen:Too many open files:bss_file.c:173:fopen('/etc/ssl/openssl.cnf','rb')
140377776379824:error:2006D002:BIO routines:BIO_new_file:system lib:bss_file.c:178:
140377776379824:error:0E078002:configuration file routines:DEF_LOAD:system lib:conf_def.c:199:

它似乎源于一个 openssl 文件,该文件在单次迭代中完成其任务后不会关闭。如果迭代不止一次,打开的文件会加起来,并且一定会在某个时候出现错误。 我仍然是一个初学者程序员,因此不想开始弄乱openSSL,所以我来这里询问,是否有解决此类问题的方法。是否可以通过在调用函数之外声明 curl 对象来解决?

【问题讨论】:

  • 如果您不在curl_handler() 内调用curl_global_cleanup(),而是在main() 末尾附近只调用一次呢?
  • @timrau,感谢您的提示,它开始将我推向正确的方向。问题是一些文件可能仍然保持打开状态,即使在清理之后,这可能会导致并发问题,但更有可能是资源过度使用。

标签: c++ curl openssl libcurl


【解决方案1】:

必须做的只是在获取数据之前声明句柄及其设置。然后在循环中仅重复实际下载及其伴随的响应。鼓励根据需要重复使用处理程序,因为它的部分资源(如在此会话中打开的文件)可能需要再次重新部署。

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 2020-11-23
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 2014-02-15
    • 2017-07-06
    • 2015-04-18
    相关资源
    最近更新 更多