From 0ec73fc148769b727b1c64abdb4a914a3e1d9ef8 Mon Sep 17 00:00:00 2001 From: mrb0nk500 Date: Fri, 4 Jun 2021 10:16:59 -0400 Subject: Added `init_daemon()`. Which actually initiallizes, and starts the daemon. If `change_dir` is true, it will change the working directory to `path`, or the root directory if `path` is NULL. --- pullreqd.c | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) (limited to 'pullreqd.c') diff --git a/pullreqd.c b/pullreqd.c index e783aa6..cb6d680 100644 --- a/pullreqd.c +++ b/pullreqd.c @@ -29,3 +29,36 @@ void child_handler(int sig_num) { void hangup_handler(int sig_num) { signal(SIGHUP, hangup_handler); } + +void init_daemon(int change_dir, char *path) { + /* Fork the parent. */ + pid_t pid = fork_proc(); + + /* Exit if the child process isn't the session leader. */ + if (setsid() < 0) { + exit(EXIT_FAILURE); + } + + /* Catch, ignore, and/or handle signals. */ + signal(SIGCHLD, child_handler); + signal(SIGHUP, hangup_handler); + + /* Fork again. */ + pid = fork_proc(); + + /* Set new file permissions. */ + umask(0); + + /* If change_dir is true, change the working directory to path, or + * the root directory if path isn't set. + */ + if (change_dir) { + chdir((!path) ? path : "/"); + } + + /* Close any open file descriptors. */ + for (int i = sysconf(_SC_OPEN_MAX); i >= 0; close(i--)); + + /* Open the logfile. */ + openlog("pullreqd", LOG_PID, LOG_DAEMON); +} -- cgit v1.2.3-13-gbd6f