common background fork
This commit is contained in:
@@ -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;
|
||||
|
@@ -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)
|
||||
|
Reference in New Issue
Block a user