c++ - curl C API : callback was not called

标签 c++ c curl callback libcurl

下面的代码是对 CURL C API 的测试。问题是永远不会调用回调函数 write_callback。为什么?

/** compilation: g++ source.cpp -lcurl */

#include <assert.h>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <curl/curl.h>

using namespace std;

static size_t write_callback(void *ptr, size_t size, size_t nmemb, void *userp)
{
    std::cerr << "CALLBACK WAS CALLED" << endl;
    exit(-1);
    return size*nmemb;
}

static void test_curl()
{
    int any_data=1;
    CURLM* multi_handle=NULL;
    CURL* handle_curl = ::curl_easy_init();
    assert(handle_curl!=NULL);
    ::curl_easy_setopt(handle_curl, CURLOPT_URL, "http://en.wikipedia.org/wiki/Main_Page");
    ::curl_easy_setopt(handle_curl, CURLOPT_WRITEDATA, &any_data);
    ::curl_easy_setopt(handle_curl, CURLOPT_VERBOSE, 1);
    ::curl_easy_setopt(handle_curl, CURLOPT_WRITEFUNCTION, write_callback);
    ::curl_easy_setopt(handle_curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");

    multi_handle = ::curl_multi_init();
    assert(multi_handle!=NULL);
    ::curl_multi_add_handle(multi_handle, handle_curl);
    int still_running=0;
    /* lets start the fetch */
    while(::curl_multi_perform(multi_handle, &still_running) ==
          CURLM_CALL_MULTI_PERFORM );
    std::cerr << "End of curl_multi_perform."<< endl;
    //cleanup should go here
    ::exit(EXIT_SUCCESS);
}

int main(int argc,char** argv)
{
    test_curl();
    return 0;
}

非常感谢

皮埃尔

最佳答案

您需要检查still_running 的值,如果仍有未决操作,则再次调用curl_multi_perform()

简单的例子:

int still_running=0;
/* lets start the fetch */
do {
    while(::curl_multi_perform(multi_handle, &still_running) ==
        CURLM_CALL_MULTI_PERFORM);
} while (still_running);

关于c++ - curl C API : callback was not called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3056925/

相关文章:

c - 如何在 C 中将 IPv6 字符串转换为无符号字符数组

c - 语法错误 : missing ';' before 'type' C code

javascript - OSRM WebAPI 参数中的负经度

c++ - 我可以强制标量类型由 int{} 初始化为零吗?

c++ - SOIL_load_image() 返回 null

c - 数组作为带参数的函数?

php - 通过 PHP cURL 将文档添加到 Apache Solr

php - 如何使用 cURL 下载在 PHP 中使用 HTTP 摘要身份验证保护的文件?

c++ - 非模板类的显式类实例化

c++ - 为什么 priority_queue 没有 front() 而有 top()