diff options
Diffstat (limited to 'platform/src/system.cpp')
| -rw-r--r-- | platform/src/system.cpp | 76 |
1 files changed, 76 insertions, 0 deletions
diff --git a/platform/src/system.cpp b/platform/src/system.cpp new file mode 100644 index 0000000..7cbdf0e --- /dev/null +++ b/platform/src/system.cpp @@ -0,0 +1,76 @@ +#include <unistd.h> +#include <string.h> +#include <errno.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <stdlib.h> + +#include "log.h" + +int run_daemon(void) +{ + int fd; + + switch (fork()) + { + // 失败 + case -1: + LOG_ERROR("Failed at fork(), %d: %s", errno, strerror(errno)); + return -1; + // 子进程 + case 0: + break; + // 父进程 + default: + exit(0); + } + + if (setsid() == -1) + { + LOG_ERROR("Failed at setsid(), %d: %s", errno, strerror(errno)); + return -1; + } + + umask(0); + + // 以读写模式打开 /dev/null + fd = open("/dev/null", O_RDWR); + if (fd == -1) + { + LOG_ERROR("Failed at open(/dev/null), %d: %s", errno, strerror(errno)); + return -1; + } + + // 将标准输入关联到 /dev/null + if (dup2(fd, STDIN_FILENO) == -1) + { + LOG_ERROR("Failed at dup2(STDIN_FILENO), %d: %s", errno, strerror(errno)); + return -1; + } + + // 将标准输出关联到 /dev/null + if (dup2(fd, STDOUT_FILENO) == -1) + { + LOG_ERROR("Failed at dup2(STDOUT_FILENO), %d: %s", errno, strerror(errno)); + return -1; + } + + // 将标准错误关联到 /dev/null + if (dup2(fd, STDERR_FILENO) == -1) + { + LOG_ERROR("Failed at dup2(STDERR_FILENO), %d: %s", errno, strerror(errno)); + return -1; + } + + // 关闭 /dev/null 的文件句柄 + if (fd > STDERR_FILENO) + { + if (close(fd) == -1) + { + LOG_ERROR("Failed at close(), %d: %s", errno, strerror(errno)); + return -1; + } + } + + return 0; +}
\ No newline at end of file |
