Skip to content

Commit 03066ed

Browse files
eddyz87Alexei Starovoitov
authored andcommitted
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 <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Alexei Starovoitov <[email protected]>
1 parent d9d4d12 commit 03066ed

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

tools/testing/selftests/bpf/Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -742,6 +742,7 @@ TRUNNER_EXTRA_SOURCES := test_progs.c \
742742
unpriv_helpers.c \
743743
netlink_helpers.c \
744744
jit_disasm_helpers.c \
745+
io_helpers.c \
745746
test_loader.c \
746747
xsk.c \
747748
disasm.c \
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
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);

0 commit comments

Comments
 (0)