Skip to content
systemcoding.dev
Networking

Queue a read with io_uring_prep_read

Queue an asynchronous file read with io_uring_prep_read in liburing 2.5 on Linux 6.8, submit it, and read the byte count from cqe->res.

1 min read
Summarize in AI

This is the smallest complete asynchronous operation: describe a read in a submission entry, hand it to the kernel, and collect the result later. io_uring_prep_read() fills in the entry for a read at a given file offset.

uring_read.cc
#include <fcntl.h>
#include <stdio.h>
#include <liburing.h>

int main(void)
{
    struct io_uring ring;
    io_uring_queue_init(8, &ring, 0);

    int fd = open("/etc/hostname", O_RDONLY);
    char buf[64];

    struct io_uring_sqe *sqe = io_uring_get_sqe(&ring);
    io_uring_prep_read(sqe, fd, buf, sizeof buf - 1, 0);
    io_uring_submit(&ring);

    struct io_uring_cqe *cqe;
    io_uring_wait_cqe(&ring, &cqe);
    int n = cqe->res;
    io_uring_cqe_seen(&ring, cqe);

    if (n >= 0) {
        buf[n] = '\0';
        printf("read %d bytes: %s", n, buf);
    }
    io_uring_queue_exit(&ring);
    return 0;
}
Text
read 5 bytes: web01

The result arrives in cqe->res and follows system call conventions with a twist: a negative value is -errno, for example -EBADF, and errno itself is not set. The buffer must stay valid until the completion arrives, so a stack buffer in a function that returns early is a bug.

For files the offset is explicit, like pread(). For sockets pass -1 or 0; the offset is ignored. io_uring_prep_recv() is the clearer choice for sockets. See io_uring_prep_read(3).

Taggedclinux
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.