From efafa6bf6822d789b15b4284c510c32d97c830ee Mon Sep 17 00:00:00 2001 From: "Scott E. Graves" Date: Mon, 4 Aug 2025 22:15:09 -0500 Subject: [PATCH] common background fork --- .../include/utils/unix/unix_utils.hpp | 2 + .../src/utils/unix/unix_utils.cpp | 51 ++++++++++++++++++- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/repertory/librepertory/include/utils/unix/unix_utils.hpp b/repertory/librepertory/include/utils/unix/unix_utils.hpp index 045f7326..a2cdf929 100644 --- a/repertory/librepertory/include/utils/unix/unix_utils.hpp +++ b/repertory/librepertory/include/utils/unix/unix_utils.hpp @@ -37,6 +37,8 @@ inline const std::array attribute_namespaces = { }; #endif +[[nodiscard]] auto create_daemon(std::function main_func) -> int; + [[nodiscard]] auto from_api_error(api_error err) -> int; [[nodiscard]] auto to_api_error(int err) -> api_error; diff --git a/repertory/librepertory/src/utils/unix/unix_utils.cpp b/repertory/librepertory/src/utils/unix/unix_utils.cpp index 80c297d1..2b4227e0 100644 --- a/repertory/librepertory/src/utils/unix/unix_utils.cpp +++ b/repertory/librepertory/src/utils/unix/unix_utils.cpp @@ -23,7 +23,7 @@ #include "utils/unix/unix_utils.hpp" -#include "utils/error_utils.hpp" +#include "utils/path.hpp" namespace repertory::utils { auto from_api_error(api_error err) -> int { @@ -223,6 +223,53 @@ void windows_create_to_unix(const UINT32 &create_options, mode |= (S_IXUSR); } } + +auto create_daemon(std::function main_func) -> int { + auto pid = fork(); + if (pid < 0) { + return 1; + } + + if (pid == 0) { + signal(SIGCHLD, SIG_DFL); + if (setsid() < 0) { + return 1; + } + + auto second_pid = fork(); + if (second_pid < 0) { + return 1; + } + + if (second_pid > 0) { + exit(0); + } + + close(STDIN_FILENO); + close(STDOUT_FILENO); + close(STDERR_FILENO); + + auto file_desc = open("/dev/null", O_RDWR); + if (file_desc < 0) { + return 1; + } + + dup2(file_desc, STDIN_FILENO); + dup2(file_desc, STDOUT_FILENO); + dup2(file_desc, STDERR_FILENO); + + if (file_desc > STDERR_FILENO) { + close(file_desc); + } + + umask(0); + chdir("/"); + return main_func(); + } + + signal(SIGCHLD, SIG_IGN); + return 0; +} } // namespace repertory::utils -#endif // !_WIN32 +#endif // !defined(_WIN32)