Skip to content

Commit ff038f9

Browse files
committed
Merge branch 'thread-safe-cloexec' of github.com:kdombroski/cpp-httplib into kdombroski-thread-safe-cloexec
2 parents e00fd06 + fb739db commit ff038f9

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

httplib.h

+23-1
Original file line numberDiff line numberDiff line change
@@ -3251,7 +3251,12 @@ socket_t create_socket(const std::string &host, const std::string &ip, int port,
32513251
const auto addrlen = host.length();
32523252
if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
32533253

3254+
#ifdef SOCK_CLOEXEC
3255+
auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC, hints.ai_protocol);
3256+
#else
32543257
auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
3258+
#endif
3259+
32553260
if (sock != INVALID_SOCKET) {
32563261
sockaddr_un addr{};
32573262
addr.sun_family = AF_UNIX;
@@ -3261,7 +3266,10 @@ socket_t create_socket(const std::string &host, const std::string &ip, int port,
32613266
hints.ai_addrlen = static_cast<socklen_t>(
32623267
sizeof(addr) - sizeof(addr.sun_path) + addrlen);
32633268

3269+
#ifndef SOCK_CLOEXEC
32643270
fcntl(sock, F_SETFD, FD_CLOEXEC);
3271+
#endif
3272+
32653273
if (socket_options) { socket_options(sock); }
32663274

32673275
if (!bind_or_connect(sock, hints)) {
@@ -3306,11 +3314,17 @@ socket_t create_socket(const std::string &host, const std::string &ip, int port,
33063314
sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
33073315
}
33083316
#else
3317+
3318+
#ifdef SOCK_CLOEXEC
3319+
auto sock = socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
3320+
#else
33093321
auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
3322+
#endif
3323+
33103324
#endif
33113325
if (sock == INVALID_SOCKET) { continue; }
33123326

3313-
#ifndef _WIN32
3327+
#if !defined _WIN32 && !defined SOCK_CLOEXEC
33143328
if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
33153329
close_socket(sock);
33163330
continue;
@@ -6505,7 +6519,15 @@ inline bool Server::listen_internal() {
65056519
#ifndef _WIN32
65066520
}
65076521
#endif
6522+
6523+
#if defined _WIN32
6524+
// sockets conneced via WASAccept inherit flags NO_HANDLE_INHERIT, OVERLAPPED
6525+
socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
6526+
#elif defined __linux__
6527+
socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
6528+
#else
65086529
socket_t sock = accept(svr_sock_, nullptr, nullptr);
6530+
#endif
65096531

65106532
if (sock == INVALID_SOCKET) {
65116533
if (errno == EMFILE) {

0 commit comments

Comments
 (0)