[dev] udp socket的read长度问题

场景描述

我的两个程序需要彼此通信。采用unix socket来实现。

并为了简单起见使用了DGRAM,也就是udp通信。

 

问题描述

1. 用法是这样的

收包的一端使用epoll监听,发包端发送一个20byte的数据包。

收包端分两次read。第一次read了16byte,第二次read,4byte。

2. 发现的问题

a。第一次read可以成功。在第一次read之后等待epoll触发(LT模式)之后,却实在等不到第二次Read的事件发送。

b。绕过epoll,改成连续两次read在一起的实现方式,发现第二次read一直返回-1,错误码为EAGAIN。

 

问题分析

DGRAM socket的特点就是这样的:你read的时候一次读不完,剩余是data有可能会被丢弃。见 man 2 recv

里边有这样的一句话:解释了问题b

If a message is too long to fit in the supplied buffer,
       excess bytes may be discarded depending on the type of socket the
       message is received from.

另一段话,解释了问题a

If no messages are available at the socket, the receive calls wait
       for a message to arrive, unless the socket is nonblocking (see
       fcntl(2)), in which case the value -1 is returned and the external
       variable errno is set to EAGAIN or EWOULDBLOCK. 

 

----------------------

完。

posted on 2019-02-14 15:52  toong  阅读(757)  评论(0编辑  收藏  举报