[英]System-call read() blocked
我有一個客戶端需要在套接字上讀取服務器發送的一系列字符。 客戶端使用系統調用 read() 讀取套接字 SOCK_DGRAM。
這里是完整的 function,內部帶有系統調用 read(..)。
ssize_t readLine(int sockd, void *vptr, size_t maxlen)
{
ssize_t n, rc;
char c, *buffer;
buffer = vptr;
for ( n = 1; n < maxlen; n++ )
{
rc = read(sockd, &c, 1);
if ( rc == 1 )
{
*buffer++ = c;
if (c == '\0') break;
}
else
{
if (errno == EINTR) continue;
return -1;
}
}
*buffer = 0;
return n;
}
問題是,如果服務器發送一個像 ABCDEF'\0' 這樣的字符序列,這個客戶端只讀取 A,然后在阻塞模式下系統調用 read() go。 我使用 Wireshark 來查看服務器是否運行良好,並且它在 UDP 數據包中正確發送 ABCDEF'\0'。 從這個角度來看一切都很好。
提前感謝大家。
使用數據報 sockets,您需要一次讀取和寫入整個數據報。
如果沒有給read
足夠的空間來讀取整個數據報,數據報的 rest 就會消失。
int datagram_length = read(sockd, vptr, maxlen - 1);
if (datagram_length < 0) {
// complain about the error
} else {
vptr[datagram_length] = 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.