2010-06-16 76 views
3

以下代碼是對C API的CURL的測試。問題是從未調用回調函數write_callback。爲什麼?CURL C API:未調用回調

/** 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; 
} 

非常感謝

皮埃爾

回答

6

您需要檢查的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); 
+2

當然您選擇()或相似爲好,否則(如果你只是複製這個例子中)的程序會忙環像瘋了似的,並使用100%的CPU – 2010-06-16 21:28:58

+0

@DanielStenberg你是什麼意思?我無法在test_curl函數中添加此示例?什麼似乎是錯的? – 2015-07-10 15:28:48

+0

你的程序會像瘋了似的忙碌循環意味着它永遠不會停頓或暫停或等待它應該 – 2015-07-18 22:41:13