Skip to content

read()

Purpose

read() reads data from a file descriptor into a userspace buffer.

It is used for regular files, device nodes, pipes, sockets, eventfd, timerfd, signalfd, and many other fd-based Linux interfaces.

#include <unistd.h>

Prototype

ssize_t read(int fd, void *buf, size_t count);

Parameters

Parameter Description
fd File descriptor to read from.
buf Destination buffer.
count Maximum number of bytes to read.

Return Value

Return Meaning
> 0 Number of bytes read.
0 End-of-file or peer closed the stream.
-1 Error. Check errno.

Minimal Example

char buf[128];
ssize_t n = read(fd, buf, sizeof(buf));
if (n < 0) {
    if (errno == EAGAIN || errno == EWOULDBLOCK)
        return 0;
    perror("read");
    return -1;
}

Common Pitfalls

  • Assuming one read() returns a complete message.
  • Not handling EINTR.
  • Not handling EAGAIN / EWOULDBLOCK for non-blocking fds.
  • Treating read() == 0 as an error for stream sockets; it usually means peer closed.