问题
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 .
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? .
Best Yash
回答1:
Linux manpages say that sockets interface doesn't support seek operations:
Seeking, or calling pread(2) or pwrite(2) with a nonzero position is not supported on sockets.
You can try issuing recv
with with the following flags set (MSG_PEEK|MSG_DONTWAIT)
specifying the buffer of a sufficient size.
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.
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.
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.
回答2:
You cannot seek on a socket handle. pread
effectively does an lseek
then a read
.
It's best to call read
or recv
in a loop and consume what is there. For a more expansive answer, see this SO question.
来源:https://stackoverflow.com/questions/11981474/pread-and-lseek-not-working-on-socket-file-descriptor