John Mike
John Mike

Reputation: 147

What happens to the data in the socket when read and write system calls are used?

This refers to C sockets. Say I have written some data into the socket, then I call read, will read system call read buffer size(say 4096 etc) information and delete all the information in the socket? Basically will read just move the seek pointer forward to those many bytes that it read or will it read and just delete all the information from socket, so that next time when read is called, it reads from the 0th index?

Or say I write into the socket without calling read from anywhere else? Will the data be replaced or appended?

Upvotes: 2

Views: 1361

Answers (1)

user149341
user149341

Reputation:

If there is more data available on a socket than the amount that you read(), the extra data will be kept in the socket's buffer until you read it. No data is lost during a short read.

Writing works similarly. If you call write() multiple times, each write will append data to the buffer on the remote host. Again, no data is lost.

(Eventually, the buffer on the remote host will fill up. When this happens, write() will block -- the local host will wait for the buffer to empty before sending more data.)

Conceptually, each direction in a socket pair behaves like a pipe between the two peers. The overall stream of data sent will be received in the same order it was sent, regardless of how much data was read/written at a time.

Upvotes: 2

Related Questions