recv with flags MSG_DONTWAIT | MSG_PEEK on TCP socket

天大地大妈咪最大 提交于 2020-01-16 18:13:44

问题


I have a TCP stream connection used to exchange messages. This is inside Linux kernel. The consumer thread keeps processing incoming messages. After consuming one message, I want to check if there are more pending messages; in which case I would process them too. My code to achieve this looks like below. krecv is wrapper for sock_recvmsg(), passing value of flags without modification (krecv from ksocket kernel module)

With MSG_DONTWAIT, I am expecting it should not block, but apparently it blocks. With MSG_PEEK, if there is no data to be read, it should just return zero. Is this understanding correct ? Is there a better way to achieve what I need here ? I am guessing this should be a common requirement as message passing across nodes is used frequently.

int recvd = 0;

do {
            recvd   += krecv(*sockp, (uchar*)msg + recvd, sizeof(my_msg) - recvd, 0); 
            printk("recvd = %d / %lu\n", recvd, sizeof(my_msg));
} while(recvd < sizeof(my_msg));
BUG_ON(recvd != sizeof(my_msg));

/* For some reason, below line _blocks_ even with no blocking flags */
recvd = krecv(*sockp, (uchar*)tempbuf, sizeof(tempbuf), MSG_PEEK | MSG_DONTWAIT);
if (recvd) {
            printk("more data waiting to be read");
            more_to_process = true;
} else {
            printk("NO more data waiting to be read");
}

回答1:


You might check buffer's length first :

int bytesAv = 0;
ioctl(m_Socket,FIONREAD,&bytesAv); //m_Socket is the socket client's fd 

If there are data in it , then recv with MSG_PEEK should not be blocked , If there are no data at all , then no need to MSG_PEEK , that might be what you like to do .



来源:https://stackoverflow.com/questions/16140802/recv-with-flags-msg-dontwait-msg-peek-on-tcp-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!