Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

linux - Can read() function on a connected socket return zero bytes?

I know that read() is a blocking call unless I make the socket non-blocking. So I expect read() call which requests 4K of data should return a positive value ( no of bytes read) or -1 on error ( possible connection reset by client etc). My question is: Can read() return '0' on any occasion?

I am handling the read() this way:

   if ((readval = read(acceptfd, buf, sizeof(buf) - 1)) < 0)
    {

    }
    else
    {
       buf[readval] = 0;
       //Do some thing with data  
    }

This code bombs if read() return zero and I know how to fix it. But is it possible for read() to return zero?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When a TCP connection is closed on one side read() on the other side returns 0 byte.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...