I am trying to read from a blocking socket, but I am wondering that read() returns -1, which I think means that there’s currently no data to read – I would expect that it blocks until it can read the amount of bytes.
I also tried ensuring that the socket is in blocking mode and that a high timeout is set using:
int setBlockingIO(int fd)
{
int flags = fcntl(fd, F_GETFL);
fcntl(fd, F_SETFL, flags & (~O_NONBLOCK));
int nTimeout = 30000; // 30 seconds
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&nTimeout, sizeof(int));
}
But this hasn’t changed anything.
My question:
- What do I have to do that
read()willreally block? - Are there some pitfalls which I might hit? (bug in my program?)
I know that there’s another question on this topic, but there I cannot find the answer for my question.
UPDATE
Without setting a timeout, read() also returns (subjectivly) immediately -1
UPDATE 2
errno is 107 (ENOTCONN, Transport endpoint is not connected).
But the client side has not closed the connection in the meanwhile (ensured by a long sleep() after write() )
It means that either there was a time-out, or possibly a signal interrupted the read. You can use the results of
errnoinerrno.hto see what the error is, and if you want the error in a human-readable formating, you can use eitherstrerror()orperror()fromstring.horstdlib.hUpdate: According to the POSIX specification, you should be passing a
struct timeval(defined insys/time.h) set to the desired number of seconds and microseconds before a timeout occurs tosetsockoptwhen specifying theSO_RCVTIMEOflag rather than casting anintto aconst char*. So even though your client may be mis-behaving and causing a different error right now, you could still end up with problems further down the line if you’re sending the wrong argument types to the function.