cURL / Mailing Lists / curl-library / Single Mail

curl-library

non-blocking code example help?

From: Christina DRS <mail_at_drsdatarecovery.com>
Date: Mon, 23 Feb 2009 09:26:57 -0500

Can anyone see if anything looks wrong with this non-blocking HTTP curl code? Will this ensure that the the code will not be blocked?

curl_global_init(CURL_GLOBAL_ALL);
CURL* easyHandle = curl_easy_init();
CURLM* multiHandle = curl_multi_init();
CURLcode errorCode = curl_easy_setopt(_easyHandle, CURLOPT_WRITEFUNCTION,&HTTPServerInterface::WriteDataCallbackFromHTTPServer);
errorCode = curl_easy_setopt(easyHandle, CURLOPT_WRITEDATA, &_messageBuffer); // the string to write the data to
errorCode = curl_easy_setopt(easyHandle, CURLOPT_URL, _url.c_str());
int still_running;
struct curl_httppost *post = NULL;
struct curl_httppost *last = NULL;
char* encoded = curl_easy_escape(easyHandle, data.c_str(), data.length());
string postit = "Report=";
postit +=encoded;
curl_easy_setopt(easyHandle, CURLOPT_POSTFIELDS, postit.c_str());
curl_easy_setopt(easyHandle, CURLOPT_POSTFIELDSIZE, postit.length());
curl_easy_setopt(easyHandle, CURLOPT_POST, 1L);
curl_multi_add_handle(multiHandle, easyHandle);

// we start some action by calling perform right away
while(CURLM_CALL_MULTI_PERFORM == curl_multi_perform(multiHandle, &still_running));
while(still_running)
{
    // set a suitable timeout to play around with
    struct timeval timeout;
    timeout.tv_sec = 1;
    timeout.tv_usec = 0;
    fd_set fdread;
    FD_ZERO(&fdread);
    fd_set fdwrite;
    FD_ZERO(&fdwrite);
    fd_set fdexcep;
    FD_ZERO(&fdexcep);
    int maxfd;

    // get file descriptors from the transfers
    curl_multi_fdset(multiHandle, &fdread, &fdwrite, &fdexcep, &maxfd);
    // make sure that maxfd is bigger than -1 so that the call to select() below makes sense!
    int rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);

    switch(rc)
    {
        case -1: // select error
            still_running = 0;
            cout << "select() error\n";
            break;
        case 0:
            default: // timeout or readable/writable sockets
            while(CURLM_CALL_MULTI_PERFORM == curl_multi_perform(multiHandle, &still_running));
            break;
    }
}

curl_multi_remove_handle(multiHandle, easyHandle);
curl_free(encoded);
Received on 2009-02-23