我对 CURLOPT_MAX_RECV_SPEED_LARGE
api 手册页有疑问。
我想设置最大下载速度,所以我补充说:
curl_off_t max_speed = 1000*25;
curl_easy_setopt(curl_handle, CURLOPT_MAX_RECV_SPEED_LARGE, max_speed);
但问题是当它达到限制(25kB/s)或我设置的值时,CPU 使用率达到 100%
我用错了吗?我想,因为我在任何地方都没有发现这个问题。我试图将这两行添加到原始示例代码中,但它也很疯狂。
我正在使用 Windows 和 libcurl v 7.29
谢谢
可能的解决方案是编写您自己的正在进行的睡眠功能,但是......
这是原始代码"getinmemory.c",我添加了 2 行:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
mem->memory =(char*) realloc(mem->memory, mem->size + realsize + 1);
if(mem->memory == NULL) {
/* out of memory! */
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
int main(void)
{
CURL *curl_handle;
CURLcode res;
struct MemoryStruct chunk;
chunk.memory = (char*)malloc(1); /* will be grown as needed by the realloc above */
chunk.size = 0; /* no data at this point */
curl_global_init(CURL_GLOBAL_ALL);
curl_handle = curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_URL, "http://ns223506.ovh.net/rozne/04e4383e647ce87ce42e73fa00bb0058/wallpaper-812988.jpg"); //Random wallpaper
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
//My added 2 lines
curl_off_t max_speed = 1000*25; // 25kB/s
curl_easy_setopt(curl_handle, CURLOPT_MAX_RECV_SPEED_LARGE, max_speed);
res = curl_easy_perform(curl_handle);
if(res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
}
else {
printf("%lu bytes retrieved\n", (long)chunk.size);
}
curl_easy_cleanup(curl_handle);
if(chunk.memory)
free(chunk.memory);
curl_global_cleanup();
return 0;
}