【发布时间】:2012-10-31 14:32:41
【问题描述】:
我在尝试使用 libcurl 下载文件时遇到问题。该程序使用多个线程,每个需要下载文件的线程都会创建一个libcurl 句柄来使用。
当 URL 正确时,一切正常,但如果 URL 中有错误,程序就会崩溃。在调试模式下,如果 URL 不正确,curl_easy_perform 返回错误连接代码,程序运行。相反,它在发布时崩溃。
我该如何解决这个错误?
这是我用来下载文件的代码,不相关的代码已被禁止:
LoadFileFromServer
(
string& a_sURL
)
{
string sErrorBuffer;
struct DownloadedFile updateFile = { sFilenameToWrite, // name to store the local file if succesful
NULL }; // temp buffer
CURL* pCurl = curl_easy_init();
curl_easy_setopt( pCurl, CURLOPT_URL, a_sURL.data() );
curl_easy_setopt( pCurl, CURLOPT_FOLLOWLOCATION, 1L );
curl_easy_setopt( pCurl, CURLOPT_ERRORBUFFER, sErrorBuffer );
curl_easy_setopt( pCurl, CURLOPT_WRITEFUNCTION, BufferToFile );
curl_easy_setopt( pCurl, CURLOPT_WRITEDATA, &updateFile );
curl_easy_setopt( pCurl, CURLOPT_NOPROGRESS, 0 );
curl_easy_setopt( pCurl, CURLOPT_CONNECTTIMEOUT, 5L );
CURLcode res = curl_easy_perform( pCurl );
curl_easy_cleanup( pCurl );
}
int BufferToFile
(
void * a_buffer,
size_t a_nSize,
size_t a_nMemb,
void * a_stream
)
{
struct DownloadedFile *out = ( struct DownloadedFile * ) a_stream;
if( out && !out->stream )
{
// open file for writing
if ( 0 != fopen_s( &( out->stream ), out->filename.c_str(), "wb" ) )
return -1;
if( !out->stream )
return -1; /* failure, can't open file to write */
}
return fwrite( a_buffer, a_nSize, a_nMemb, out->stream );
}
【问题讨论】:
-
您能否编辑问题以包含错误的 URL?
-
它是如何崩溃的?它是段错误还是您尝试查看它是否引发异常?您是否尝试过通过调试器运行?
-
LoadFileFromServer是如何被调用的?这个函数的参数,一个字符串引用,是否在各个线程之间共享? -
URL 不正确,因为主机名无效。
-
我尝试在代码中引入 try/catch,但它还是崩溃了,没有异常可以捕获。在调试中它工作正常,curl_easy_perform 返回错误连接代码。
标签: c++ multithreading curl libcurl