卷曲导致openssl错误

Curl causes openssl error

本文关键字:openssl 错误      更新时间:2023-10-16

我当前的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对象来解决吗?

所要做的就是在获取数据之前简单地声明句柄及其设置。然后,只有实际的下载及其伴随的响应才会在循环中被重申。鼓励根据需要经常重用处理程序,因为它的部分资源(如在该会话中打开的文件)可能需要再次重新部署。