common background fork

This commit is contained in:
2025-08-04 22:15:09 -05:00
parent e88d53760d
commit efafa6bf68
2 changed files with 51 additions and 2 deletions

View File

@@ -37,6 +37,8 @@ inline const std::array<std::string, 4U> attribute_namespaces = {
};
#endif
[[nodiscard]] auto create_daemon(std::function<int()> main_func) -> int;
[[nodiscard]] auto from_api_error(api_error err) -> int;
[[nodiscard]] auto to_api_error(int err) -> api_error;

View File

@@ -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<int()> 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)