pread 和 lseek 无法处理套接字文件描述符 [英] pread and lseek not working on socket file descriptor
问题描述
这个问题是关于系统调用 pread 和 lseek 的.我有一个套接字类型的文件描述符.每当从网络层读取数据包时,就会向其中添加数据.我想知道定期出现在文件描述符中的数据量是多少.
This question is on system calls pread and lseek . I have a file descriptor of socket type . Data is added to it whenever packet is read from the network layer . I would like to know whats the amount of data present in the file descriptor at regular intervals .
我尝试使用系统调用 pread 和 lseek ,因此我只知道数据量而不是读取数据本身.但是,这两个调用都失败了,给出了非法搜索错误.套接字类型文件描述符上是否有任何其他系统调用或套接字 fd 不支持 pread 和 lseek?.
I tried using the systems calls pread and lseek , so that I know only the amount of data rather than reading data itself . But , both the calls fails giving Illegal seek error. Are there any other systems calls on the socket type file descriptor or pread and lseek are not supported on socket fd? .
最好的亚什
推荐答案
Linux 联机帮助页说sockets接口不支持seek操作:
Linux manpages say that sockets interface doesn't support seek operations:
寻找或调用具有非零位置的 pread(2) 或 pwrite(2) 是套接字不支持.
Seeking, or calling pread(2) or pwrite(2) with a nonzero position is not supported on sockets.
您可以尝试使用以下标志设置 (MSG_PEEK|MSG_DONTWAIT)
指定足够大小的缓冲区来发出 recv
.
You can try issuing recv
with with the following flags set (MSG_PEEK|MSG_DONTWAIT)
specifying the buffer of a sufficient size.
此操作将从套接字的接收缓冲区中复制数据,但不会将其弹出,即后续的 recv
/read
调用将读取所有相同的数据 + 一些更多的数据可能到达套接字,因此返回的字节数可能更大.
This operation will copy the data from socket's receive buffer, but won't pop it out i.e. a subsequent recv
/read
call will read all the same data + some more data might arrive on socket so the number of bytes returned might be even greater.
缓冲区大小是一个非常棘手的问题 - 它应该大于套接字接收缓冲区,否则您的 recv
调用可能会返回您的缓冲区中的字节数提供,但插座实际上还有更多.
The buffer size is a very sticky point there - it should be greater than the socket receive buffer, otherwise there is a chance your recv
call will return the number of bytes there are in the buffer you provided, but the socket actually has some more.
套接字接收缓冲区的大小可以通过带有选项名称SO_RCVBUF
的getsockopt
函数获得.
The size of the socket receive buffer can be obtained by means of getsockopt
function with the option name SO_RCVBUF
.
顺便说一句,我认为更好的选择是实际读取数据并将其保存在缓冲区中的某处.当您阅读了足够多的数据后,对其进行一些操作.与不提取数据直接查看套接字接收缓冲区相比,这似乎是一种更好、更常见的方法.
Btw, I think a better option would be to actually read the data and keep it in the buffer somewhere. When you've read enough data, do some actions with it. This seems to be a better and more common approach than peeking into the socket receive buffer without extracting data.
这篇关于pread 和 lseek 无法处理套接字文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!