2012-02-23 39 views
0

我正在用libcurl在C中編寫一個小的下載管理器,並且遇到了一個有趣的問題。看來,我沒有正確理解如何curl_multi_perform作品到現在爲止,有一次我發現了這個主循環實際上僅下載每處理每秒16昆明植物研究所:在一個主循環中顯示狀態並執行下載

while (1) { 
    int cmp_rem; 
    j_recount_speeds(); 
    j_handle_completed(); 
    j_handle_waiting(); 
    curl_multi_perform(j_curlm, &cmp_rem); 
    j_status(); 
    sleep(1); 
} 

我有看一些examples on cURL's website涉及多接口,和發現正確的做法是在套接字文件描述符select上調用curl_multi_perform一次就緒。儘管如此,我希望能夠以規則的時間間隔運行j_recount_speeds,j_handle_completed,j_handle_waitingj_status。我能做到這一點以及我需要在一個主循環中使用curl_multi_perform,還是需要使用單獨的線程?

回答

1

你不需要單獨的線程,你只需要瞭解什麼接口可供你使用。首先,你可以用超時發出select():

while (continue_condition_true) { 
    struct timeval tv = { 1, 0 }; /* 1 second, zero microseconds */ 

    /* Select returns 0 if it has timed out */ 
    if (select(nfds, readfds, writefds, exceptfds, &tv) == 0) { 
     /* perform timeout operations here */ 
     continue; 
    } 
} 

請注意,這需要真正的錯誤檢查從選擇的返回值();此代碼僅供寓教於樂!

其次,你可以使用函數gettimeofday()來檢查經過時間:

struct timeval base_tv, tmp_tv; 

gettimeofday(&base_tv, NULL); 

/* do your processing here */ 

gettimeofday(&tmp_tv, NULL); 

if (tmp_tv.tv_sec - base_tv.tv_sec > 0) { 
    /* perform timeout operations here */ 

    /* update base_tv to new 'base' time */ 
    gettimeofday(&base_tv, NULL); 
} 

這是當然的,只是一個過程超時(並忽略微秒的比較),但對於更新的目的用戶的cURL顯示應該足夠了。

編輯:

從CURLM結構提取fdset信息出現時,根據文檔,去正是如此:

fd_set readfds, writefds, exceptfds; 
struct timeout tv = { 1, 0 }; /* 1-second timeout */ 
int nfds; 

/* extract fd_set data from CURLM data */ 
curl_multi_fdset(curlm, &readfds, &writefds, &exceptfds, &nfds); 
select(nfds, &readfds, &writefds, &exceptfds, &tv); 

再次,寓教於樂而已,真正的錯誤處理代碼需要去在在這裏,納尼亞的保修無效等。

+0

請問你能否詳細解釋'select'是如何在'curl_multi_perform'的環境下工作的?由於我在這方面非常陌生,我不確定這是如何工作的以及如何修改我的代碼。根據http://curl.haxx.se/libcurl/c/curl_multi_perform.html的 – 2012-02-23 11:29:55

+0

,你可以調用curl_multi_fdset(http://curl.haxx.se/libcurl/c/curl_multi_fdset.html)來檢索你想要的fdset然後傳遞給select();快速示例將很快公佈。 – tbert 2012-02-23 11:36:39

+0

感謝您的回答。我現在很忙,沒有機會擺弄我的代碼,所以我提前道歉在接受你的答案之前花一些時間。 – 2012-02-24 12:14:58