Files
DarkflameServer/tests/dCommonTests/ProcessFdTests.cpp
Aaron Kimbrell 4936e8103a fix(master): servers master starts no longer inherit its sockets
The child closes every descriptor above 2 before exec, so master's UDP
ports are released when master stops. Process::Run closes them too.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 20:38:15 -06:00

45 lines
1.4 KiB
C++

#include <gtest/gtest.h>
#include "Process.h"
#ifdef __linux__
#include <string>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
namespace {
// Starts `sh -c <script>` the way master starts a server; returns its exit code
int SpawnLikeMaster(const std::string& script, const bool closeFds) {
const auto pid = fork();
if (pid == 0) {
if (closeFds) Process::CloseInheritedFds();
execl("/bin/sh", "sh", "-c", script.c_str(), nullptr);
_exit(127);
}
int status = 0;
waitpid(pid, &status, 0);
return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}
}
TEST(ProcessFdTests, ChildDoesNotKeepTheParentsSockets) {
const int sock = socket(AF_INET, SOCK_DGRAM, 0); // no close-on-exec, like a socket a library opens
ASSERT_GE(sock, 3);
const auto check = "[ -e /proc/self/fd/" + std::to_string(sock) + " ]";
// Without the close the program still holds it (the check passes: exit 0), with it the fd is gone (exit 1)
EXPECT_EQ(SpawnLikeMaster(check, false), 0);
EXPECT_EQ(SpawnLikeMaster(check, true), 1);
close(sock);
}
TEST(ProcessFdTests, RunDoesNotKeepTheParentsSockets) {
const int sock = socket(AF_INET, SOCK_DGRAM, 0);
ASSERT_GE(sock, 3);
// sh -c 'ls /proc/self/fd' would list the fds; the program must only see 0, 1, 2 and the one ls opens
const auto status = Process::Run({ "/bin/sh", "-c", "[ ! -e /proc/self/fd/" + std::to_string(sock) + " ]" });
EXPECT_EQ(status, 0);
close(sock);
}
#endif