Skip to content

Commit b0a189e

Browse files
committed
Sketch handling EINTR errors
1 parent 776b3ff commit b0a189e

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

httplib.h

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,18 @@ inline const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *asn1) {
172172
#endif
173173
#endif
174174

175+
#define HANDLE_EINTR(method, ...) \
176+
({int res; \
177+
while (true) { \
178+
res = method(__VA_ARGS__); \
179+
if (res < 0 && errno == EINTR) { \
180+
continue; \
181+
} else { \
182+
break; \
183+
} \
184+
} \
185+
res;})
186+
175187
#ifdef CPPHTTPLIB_ZLIB_SUPPORT
176188
#include <zlib.h>
177189
#endif
@@ -1206,7 +1218,7 @@ inline int select_read(socket_t sock, time_t sec, time_t usec) {
12061218

12071219
auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
12081220

1209-
return poll(&pfd_read, 1, timeout);
1221+
return HANDLE_EINTR(poll, &pfd_read, 1, timeout);
12101222
#else
12111223
fd_set fds;
12121224
FD_ZERO(&fds);
@@ -1228,7 +1240,7 @@ inline int select_write(socket_t sock, time_t sec, time_t usec) {
12281240

12291241
auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
12301242

1231-
return poll(&pfd_read, 1, timeout);
1243+
return HANDLE_EINTR(poll, &pfd_read, 1, timeout);
12321244
#else
12331245
fd_set fds;
12341246
FD_ZERO(&fds);
@@ -1250,13 +1262,13 @@ inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) {
12501262

12511263
auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
12521264

1253-
if (poll(&pfd_read, 1, timeout) > 0 &&
1254-
pfd_read.revents & (POLLIN | POLLOUT)) {
1265+
int poll_res = HANDLE_EINTR(poll, &pfd_read, 1, timeout);
1266+
if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
12551267
int error = 0;
12561268
socklen_t len = sizeof(error);
1257-
return getsockopt(sock, SOL_SOCKET, SO_ERROR,
1258-
reinterpret_cast<char *>(&error), &len) >= 0 &&
1259-
!error;
1269+
int res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
1270+
reinterpret_cast<char *>(&error), &len);
1271+
return res >= 0 && !error;
12601272
}
12611273
return false;
12621274
#else
@@ -2947,7 +2959,7 @@ inline ssize_t SocketStream::read(char *ptr, size_t size) {
29472959
}
29482960
return recv(sock_, ptr, static_cast<int>(size), 0);
29492961
#else
2950-
return recv(sock_, ptr, size, 0);
2962+
return HANDLE_EINTR(recv, sock_, ptr, size, 0);
29512963
#endif
29522964
}
29532965

@@ -5099,3 +5111,4 @@ inline std::shared_ptr<Response> Get(const char *url) {
50995111
} // namespace httplib
51005112

51015113
#endif // CPPHTTPLIB_HTTPLIB_H
5114+

0 commit comments

Comments
 (0)