123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- #include "daemonize.h"
- #include "logging.h"
- #include <fcntl.h>
- #include <stdlib.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <unistd.h>
- void daemonize(const char *name)
- {
-
- pid_t pid = fork();
- if (pid < 0) {
- FATAL_ERRORNO("Failed to fork");
- }
- if (pid != 0) {
- LOG_MSG("Daemon launched as %s...\n", name);
- exit(EXIT_SUCCESS);
- }
-
- pid = fork();
- if (pid < 0) {
- FATAL_ERRORNO("Failed to fork");
- } else if (pid > 0) {
- exit(EXIT_SUCCESS);
- }
-
- umask(0022);
- if (setsid() < 0) {
- FATAL_ERRORNO("Failed to create process group\n");
- }
- if (chdir("/") < 0) {
- FATAL_ERRORNO("Failed to change to root directory\n");
- }
-
- int devnull_r = open("/dev/null", O_RDONLY);
- int devnull_w = open("/dev/null", O_WRONLY);
- dup2(devnull_r, STDIN_FILENO);
- dup2(devnull_w, STDOUT_FILENO);
- dup2(devnull_w, STDERR_FILENO);
- close(devnull_r);
- close(devnull_w);
- }
|