具有标志MSG_DONTWAIT的recv | TCP套接字上的MSG_PEEK [英] recv with flags MSG_DONTWAIT | MSG_PEEK on TCP socket

查看:1633
本文介绍了具有标志MSG_DONTWAIT的recv | TCP套接字上的MSG_PEEK的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个TCP流连接用于交换消息.这在Linux内核中.使用者线程继续处理传入的消息.消费完一条消息后,我想检查是否还有更多待处理的消息.在这种情况下,我也会处理它们.我实现此目的的代码如下所示. krecv是sock_recvmsg()的包装器,无需修改即可传递标志的值(来自 ksocket内核模块的krecv)

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)

对于MSG_DONTWAIT,我希望它不应该阻止,但是显然它可以阻止.对于MSG_PEEK,如果没有要读取的数据,则应仅返回零.这种理解正确吗?有没有更好的方法来实现我在这里所需要的?我猜这应该是一个普遍的要求,因为跨节点的消息传递经常被使用.

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.问题所在
2.我面对它.

This is a very-very old question, but
1. problem persits
2. I faced with it.

至少对我来说(使用python 2.7的Ubuntu 16.04)对此MSG_DONTWAIT无效,但是,如果我将超时设置为零(使用settimeout函数),则效果很好. 可以使用setockopt函数在c语言中完成此操作.

At least for me (Ubuntu 19.04 with python 2.7) this MSG_DONTWAIT has no effect, however if I set the timeout to zero (with settimeout function), it works nicely.
This can be done in c with setsockopt function.

这篇关于具有标志MSG_DONTWAIT的recv | TCP套接字上的MSG_PEEK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆