diff --git a/examples/helpers.c b/examples/helpers.c index 7d80b71..26fbce7 100644 --- a/examples/helpers.c +++ b/examples/helpers.c @@ -37,6 +37,7 @@ #include #include #include +#include int openlistener_socket(int port) { @@ -115,3 +116,55 @@ int normalize_path(char *path) return 0; } + +#define DM_MAX_CLOSE 8192 + +int daemonize(void) +{ + pid_t pid; + + /* fork */ + pid = fork(); + if (pid == -1) { + perror("fork() failed"); + return EFAULT; + } + else if (pid != 0) { + exit(EXIT_SUCCESS); + } + + /* create new session and progress group */ + if (setsid() == -1) { + perror("setsid() failed"); + return EFAULT; + } + + /* set the working directory to the root directory */ + if (chdir("/") == -1) { + perror("chdir() failed"); + return EFAULT; + } + + /* close all open files */ + int fd; + int maxfd = sysconf(_SC_OPEN_MAX); + if (maxfd == -1) + maxfd = DM_MAX_CLOSE; /* if this limit is indeterminate, take a guess */ + for (fd = 0; fd < maxfd; fd++) + close(fd); + + /* reopen standard fd's /dev/null */ + close(STDIN_FILENO); + fd = open("/dev/null", O_RDWR); + if (fd != STDIN_FILENO) { /* fd should be 0 */ + return EBADFD; + } + if (dup2(STDIN_FILENO, STDOUT_FILENO) != STDOUT_FILENO) { + return EBADFD; + } + if (dup2(STDIN_FILENO, STDERR_FILENO) != STDERR_FILENO) { + return EBADFD; + } + + return 0; +} \ No newline at end of file diff --git a/examples/helpers.h b/examples/helpers.h index 9f40902..dc0adfe 100644 --- a/examples/helpers.h +++ b/examples/helpers.h @@ -36,4 +36,6 @@ static inline void version_print(FILE *fso) } #endif +int daemonize(void); + #endif /* __SXMP_EXAMPLES_HELPERS_H__ */