Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this blocking socket read return zero and no error?

Tags:

c

linux

io

sockets

This code running on Linux:

int r, c;
...
assert(0 == (O_NONBLOCK & fcntl(sockfd, F_GETFL, 0)));
errno = 0;
r = read(sockfd, &c, 1);
if (r == 0 && errno == 0) { 
    printf("What gives?\n");
}
...

which is performing a read from a socket, will occasionally return zero (in r) and leave errno set to zero (0) as well. What situation am I encountering? I'd really like to have the read block unless there is an error.

like image 347
Jamie Avatar asked May 08 '26 17:05

Jamie


2 Answers

This means that the client finished sending data (eg: did a shutdown for writing), and you already read all available data.

RETURN VALUE

On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number.

like image 89
Karoly Horvath Avatar answered May 10 '26 10:05

Karoly Horvath


Generally the read man page says:

On success, the number of bytes read is returned (zero indicates end of file)

so 0 means that your socket is closed.

like image 24
Jens Gustedt Avatar answered May 10 '26 10:05

Jens Gustedt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!