xref: /linux/tools/testing/selftests/bpf/io_helpers.c (revision 60675d4ca1ef0857e44eba5849b74a3a998d0c0f)
1*03066ed3SEduard Zingerman // SPDX-License-Identifier: GPL-2.0
2*03066ed3SEduard Zingerman #include <sys/select.h>
3*03066ed3SEduard Zingerman #include <unistd.h>
4*03066ed3SEduard Zingerman #include <errno.h>
5*03066ed3SEduard Zingerman 
6*03066ed3SEduard Zingerman int read_with_timeout(int fd, char *buf, size_t count, long usec)
7*03066ed3SEduard Zingerman {
8*03066ed3SEduard Zingerman 	const long M = 1000 * 1000;
9*03066ed3SEduard Zingerman 	struct timeval tv = { usec / M, usec % M };
10*03066ed3SEduard Zingerman 	fd_set fds;
11*03066ed3SEduard Zingerman 	int err;
12*03066ed3SEduard Zingerman 
13*03066ed3SEduard Zingerman 	FD_ZERO(&fds);
14*03066ed3SEduard Zingerman 	FD_SET(fd, &fds);
15*03066ed3SEduard Zingerman 	err = select(fd + 1, &fds, NULL, NULL, &tv);
16*03066ed3SEduard Zingerman 	if (err < 0)
17*03066ed3SEduard Zingerman 		return err;
18*03066ed3SEduard Zingerman 	if (FD_ISSET(fd, &fds))
19*03066ed3SEduard Zingerman 		return read(fd, buf, count);
20*03066ed3SEduard Zingerman 	return -EAGAIN;
21*03066ed3SEduard Zingerman }
22