[英]Thread not updating but blocking on recv()
我正在制作一個多線程TCP服務器,當我在線程中使用recv()時,它們不會無限地更新/執行/運行(循環),除非recv()實際上接收到一些數據。
這是循環內部的代碼片段。
if( seconds < 15 ){
printf("%f seconds passed: \r", seconds);
if ( (read_size = recv(sock , client_message , 512 , 0)) > 0 )
{
//Send the message back to client
reply_message = client_message;
(void)write(sock, reply_message, strlen(reply_message));
}
}else{
// ... blah blah blah
}
如果我注釋掉內部IF語句,則線程將以最快的速度運行並輸出printf()。 當包含IF語句時,線程將在recv()上等待,直到recv()接收到數據后才會更新(不打印printf()):/
有任何想法嗎?
從recv(2)-Linux手冊頁(請參閱此處 ):
如果套接字上沒有可用的消息,則接收調用將等待消息到達,除非套接字是非阻塞的(請參閱fcntl(2)),在這種情況下,將返回值-1且外部變量errno設置為EAGAIN或EWOULDBLOCK。 接收呼叫通常返回不超過請求數量的任何可用數據,而不是等待接收請求的全部數量。
這就是recv
工作方式。 如果希望它立即返回,則應使用非阻塞模式(請參閱fcntl
並select
)。
// sock is the socket you want to make non-blocking
int status = fcntl(sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK);
// handle the error
if(status == -1) {
...
}
如果要檢查套接字中是否有任何內容
int count = 0;
ioctl(sock, FIONREAD, &count);
count
是套接字中可用的字節數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.