Andrew Sun
Andrew Sun

Reputation: 4231

Is read guaranteed to return as soon as data is available?

I want to implement a simple notification protocol using TCP sockets. The server will write a byte to a socket to notify the client, and the client reads from the socket, waiting until some data arrives, at which point it can return from the read call and perform some work.

while (1) {
    /* Wait for any notifications */
    char buf[32];
    if (read(fd, buf, sizeof(buf)) <= 0) {
        break;
    }

    /* Received notification */
    do_work();
}

My question is, is read guaranteed to return as soon as any data is available to read, or is the kernel allowed to keep waiting until some condition is met (e.g. some minimum number of bytes received, not necessarily the count which I pass into read) before it returns from the read call? If the latter is true, is there a flag that will disable that behavior?

I am aware that I could use the O_NONBLOCK flag and call read in a loop, but the purpose of this is to use as little CPU time as possible.

Upvotes: 0

Views: 106

Answers (1)

that other guy
that other guy

Reputation: 123400

There are multiple implicit questions here:

Is read guaranteed to return immediately or shortly after a relevant event?

No. The kernel is technically allowed to make you wait as long as it wants.

In practice, it'll return immediately (modulo rescheduling delays).

This is true for poll and O_NONBLOCK as well. Linux is not a realtime OS, and offers no hard timing guarantees, just its best effort.

Is read allowed to wait indefinitely for multiple bytes to become available?

No, this would cause deadlocks. read needs to be able to return with a single byte, even if there are no guarantees about when it will do so.

In practice, Linux makes the same effort for 1 byte as it does for 1,048,576.

Is sending a single byte on a socket a practical way of waking up a remote process as soon as possible?

Yes, your example is perfectly fine.

Upvotes: 1

Related Questions