1 | /* |
2 | Simple DirectMedia Layer |
3 | Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org> |
4 | |
5 | This software is provided 'as-is', without any express or implied |
6 | warranty. In no event will the authors be held liable for any damages |
7 | arising from the use of this software. |
8 | |
9 | Permission is granted to anyone to use this software for any purpose, |
10 | including commercial applications, and to alter it and redistribute it |
11 | freely, subject to the following restrictions: |
12 | |
13 | 1. The origin of this software must not be misrepresented; you must not |
14 | claim that you wrote the original software. If you use this software |
15 | in a product, an acknowledgment in the product documentation would be |
16 | appreciated but is not required. |
17 | 2. Altered source versions must be plainly marked as such, and must not be |
18 | misrepresented as being the original software. |
19 | 3. This notice may not be removed or altered from any source distribution. |
20 | */ |
21 | |
22 | #include "../../SDL_internal.h" |
23 | |
24 | #include "SDL_poll.h" |
25 | |
26 | #ifdef HAVE_POLL |
27 | #include <poll.h> |
28 | #else |
29 | #include <sys/time.h> |
30 | #include <sys/types.h> |
31 | #include <unistd.h> |
32 | #endif |
33 | #include <errno.h> |
34 | |
35 | |
36 | int |
37 | SDL_IOReady(int fd, SDL_bool forWrite, int timeoutMS) |
38 | { |
39 | int result; |
40 | |
41 | /* Note: We don't bother to account for elapsed time if we get EINTR */ |
42 | do |
43 | { |
44 | #ifdef HAVE_POLL |
45 | struct pollfd info; |
46 | |
47 | info.fd = fd; |
48 | if (forWrite) { |
49 | info.events = POLLOUT; |
50 | } else { |
51 | info.events = POLLIN | POLLPRI; |
52 | } |
53 | result = poll(&info, 1, timeoutMS); |
54 | #else |
55 | fd_set rfdset, *rfdp = NULL; |
56 | fd_set wfdset, *wfdp = NULL; |
57 | struct timeval tv, *tvp = NULL; |
58 | |
59 | /* If this assert triggers we'll corrupt memory here */ |
60 | SDL_assert(fd >= 0 && fd < FD_SETSIZE); |
61 | |
62 | if (forWrite) { |
63 | FD_ZERO(&wfdset); |
64 | FD_SET(fd, &wfdset); |
65 | wfdp = &wfdset; |
66 | } else { |
67 | FD_ZERO(&rfdset); |
68 | FD_SET(fd, &rfdset); |
69 | rfdp = &rfdset; |
70 | } |
71 | |
72 | if (timeoutMS >= 0) { |
73 | tv.tv_sec = timeoutMS / 1000; |
74 | tv.tv_usec = (timeoutMS % 1000) * 1000; |
75 | tvp = &tv; |
76 | } |
77 | |
78 | result = select(fd + 1, rfdp, wfdp, NULL, tvp); |
79 | #endif /* HAVE_POLL */ |
80 | |
81 | } while ( result < 0 && errno == EINTR ); |
82 | |
83 | return result; |
84 | } |
85 | |
86 | /* vi: set ts=4 sw=4 expandtab: */ |
87 | |