I am very new to libcurl. So any help is appreciated.
I am trying to download multiple files from CDN. The total size is around 600mb. This is the piece of code where I am setting CURL handles(Inside a method named "addTransfers()"). (cm is of type CURLM*)
CURL *ceh = curl_easy_init();
curl_easy_setopt(ceh, CURLOPT_URL, reqURL.c_str());
curl_easy_setopt(ceh, CURLOPT_USERPWD, usrpwd);
curl_easy_setopt(ceh, CURLOPT_WRITEDATA, file);
curl_easy_setopt(ceh, CURLOPT_PRIVATE, file);
curl_easy_setopt(ceh, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(ceh, CURLOPT_FAILONERROR, 1L);
curl_easy_setopt(ceh, CURLOPT_CONNECTTIMEOUT, 10L);
curl_easy_setopt(ceh, CURLOPT_TIMEOUT, 150L);
curl_multi_add_handle(cm, ceh);
This is the code where I am performing the curl multi process:
bool do_multiple_downloads()
{
CURLM *cm;
CURLMsg *msg;
unsigned int transfers = 0;
int pending = 1;
int msg_pending = -1;
curl_global_init(CURL_GLOBAL_ALL);
cm = curl_multi_init();
curl_multi_setopt(cm, CURLMOPT_MAXCONNECTS, maxConnects);
for(transfers = 0; transfers < (int)maxConnects; transfers++)
{
if(!addTransfers(cm, transfers))
{
//Error
return false;
}
}
int i = 0;
do
{
/* code */
CURLMcode cPerformCode = curl_multi_perform(cm, &pending);
if(cPerformCode != CURLM_OK)
{
fprintf(stderr, "Error --> (%s) : Pending --> (%d)", curl_multi_strerror(cPerformCode), pending);
return false;
}
while((msg = curl_multi_info_read(cm, &msg_pending)))
{
if(msg != NULL)
{
if(msg->msg == CURLMSG_DONE)
{
FILE* writtenFile;
char* fname;
CURL *e = msg->easy_handle;
curl_easy_getinfo(e, CURLINFO_PRIVATE, &writtenFile);
fprintf(stderr, "R: %d - %s (%d)\n",
msg->data.result, curl_easy_strerror(msg->data.result), i++);
curl_multi_remove_handle(cm, e);
fclose(writtenFile);
curl_easy_cleanup(e);
}
else
{
fprintf(stderr, "E: CURLMsg (%d) : (%d)\n", msg->msg, i++);
}
if(transfers < totalSize)
{
if(!addTransfers(cm, transfers++))
{
//Error
fprintf(stderr, "Additional transfers addition\n");
return false;
}
}
}
}
if(pending)
{
curl_multi_wait(cm, NULL, 0, 1000, NULL);
}
} while (pending || (transfers < totalSize));
curl_multi_cleanup(cm);
curl_global_cleanup();
return true;
}
These are the scenarios:
- Sometimes it works fine and all files are downloaded - No problem
- Sometimes the downloads are completed, but the program is still inside the do-while loop(pending variable never becomes zero)
- If I disconnect from the internet when the process is happening, the program stays inside the do-while loop. When I reconnect to the internet, Scenario 2 occurs.
Am I missing something here?? I might have done something silly here. Not sure though. Thanks in advance.