1 // SPDX-License-Identifier: GPL-2.0
2 #include <sys/select.h>
3 #include <unistd.h>
4 #include <errno.h>
5
read_with_timeout(int fd,char * buf,size_t count,long usec)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 }
22