aboutsummaryrefslogtreecommitdiff
path: root/src/utils.c
diff options
context:
space:
mode:
authorToni Uhlig <matzeton@googlemail.com>2018-04-05 17:53:27 +0200
committerToni Uhlig <matzeton@googlemail.com>2018-04-07 00:03:28 +0200
commitebabaa69c0a3ba992895c7a66729e81e0923d5f1 (patch)
tree39b4a5b90a4f51c98486e8a00898e983b8878a12 /src/utils.c
Initial commit.
Signed-off-by: Toni Uhlig <matzeton@googlemail.com>
Diffstat (limited to 'src/utils.c')
-rw-r--r--src/utils.c74
1 files changed, 74 insertions, 0 deletions
diff --git a/src/utils.c b/src/utils.c
new file mode 100644
index 0000000..5c86017
--- /dev/null
+++ b/src/utils.c
@@ -0,0 +1,74 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <signal.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <syslog.h>
+
+#include "utils.h"
+
+#define _POSIX_PATH_MAX 256
+
+
+void set_procname(char *arg0, const char *newname)
+{
+ memset(arg0, 0, _POSIX_PATH_MAX);
+ strncpy(arg0, newname, _POSIX_PATH_MAX);
+}
+
+int daemonize(void)
+{
+ pid_t pid;
+
+ /* Fork off the parent process */
+ pid = fork();
+
+ /* An error occurred */
+ if (pid < 0)
+ exit(EXIT_FAILURE);
+
+ /* Success: Let the parent terminate */
+ if (pid > 0)
+ exit(EXIT_SUCCESS);
+
+ /* On success: The child process becomes session leader */
+ if (setsid() < 0)
+ exit(EXIT_FAILURE);
+
+ /* Catch, ignore and handle signals */
+ //TODO: Implement a working signal handler */
+ signal(SIGCHLD, SIG_IGN);
+ signal(SIGHUP, SIG_IGN);
+
+ /* Fork off for the second time*/
+ pid = fork();
+
+ /* An error occurred */
+ if (pid < 0)
+ exit(EXIT_FAILURE);
+
+ /* Success: Let the parent terminate */
+ if (pid > 0)
+ exit(EXIT_SUCCESS);
+
+ /* Set new file permissions */
+ umask(0);
+
+ /* Change the working directory to the root directory */
+ /* or another appropriated directory */
+ chdir("/");
+
+ /* Close all open file descriptors */
+ int x;
+ for (x = sysconf(_SC_OPEN_MAX); x>=0; x--)
+ {
+ close (x);
+ }
+
+ /* Open the log file */
+ openlog ("firstdaemon", LOG_PID, LOG_DAEMON);
+
+ return 0;
+}