Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

selftests/bpf: add read_with_timeout() utility function

int read_with_timeout(int fd, char *buf, size_t count, long usec)

As a regular read(2), but allows to specify a timeout in
micro-seconds. Returns -EAGAIN on timeout.
Implemented using select().

Signed-off-by: Eduard Zingerman <eddyz87@gmail.com>
Link: https://lore.kernel.org/r/20241112110906.3045278-3-eddyz87@gmail.com
Signed-off-by: Alexei Starovoitov <ast@kernel.org>

authored by

Eduard Zingerman and committed by
Alexei Starovoitov
03066ed3 d9d4d127

+29
+1
tools/testing/selftests/bpf/Makefile
··· 742 742 unpriv_helpers.c \ 743 743 netlink_helpers.c \ 744 744 jit_disasm_helpers.c \ 745 + io_helpers.c \ 745 746 test_loader.c \ 746 747 xsk.c \ 747 748 disasm.c \
+21
tools/testing/selftests/bpf/io_helpers.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + #include <sys/select.h> 3 + #include <unistd.h> 4 + #include <errno.h> 5 + 6 + int read_with_timeout(int fd, char *buf, size_t count, long usec) 7 + { 8 + const long M = 1000 * 1000; 9 + struct timeval tv = { usec / M, usec % M }; 10 + fd_set fds; 11 + int err; 12 + 13 + FD_ZERO(&fds); 14 + FD_SET(fd, &fds); 15 + err = select(fd + 1, &fds, NULL, NULL, &tv); 16 + if (err < 0) 17 + return err; 18 + if (FD_ISSET(fd, &fds)) 19 + return read(fd, buf, count); 20 + return -EAGAIN; 21 + }
+7
tools/testing/selftests/bpf/io_helpers.h
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + #include <unistd.h> 3 + 4 + /* As a regular read(2), but allows to specify a timeout in micro-seconds. 5 + * Returns -EAGAIN on timeout. 6 + */ 7 + int read_with_timeout(int fd, char *buf, size_t count, long usec);