#include #include #include #include #include #include #include #include #include #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); } pid_t daemonize(int stay_foreground) { int status = -1; pid_t pid; /* Fork off the parent process */ pid = fork(); /* An error occurred */ if (pid < 0) return pid; /* Success: Let the parent terminate */ if (pid > 0) { if (!stay_foreground) exit(EXIT_SUCCESS); waitpid(-1, &status, 0); exit(EXIT_SUCCESS); } /* On success: The child process becomes session leader */ if (!stay_foreground && setsid() < 0) exit(EXIT_FAILURE); /* Catch, ignore and handle signals */ //TODO: Implement a working signal handler */ //signal(SIGCHLD, SIG_IGN); //signal(SIGHUP, SIG_IGN); if (!stay_foreground) { /* 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); if (stay_foreground) return pid; /* 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); } return pid; }