void daemonize(const char *cmd) { int i, fd0, fd1, fd2; pid_t pid; struct rlimit rl; struct sigaction sa;
/* * Clear file creation mask. */ umask(0);
/* * Get maximum number of file descriptors. */ if (getrlimit(RLIMIT_NOFILE, &rl) < 0) { fprintf(stderr, "%s: can't get file limit: %s\n", cmd, (char *)strerror(errno)); exit(-1); }
/* * Become a session leader to lose controlling TTY. */ if ((pid = fork()) < 0) { fprintf(stderr, "%s: can't fork: %s\n", cmd, (char *)strerror(errno)); exit(-1); } else if (pid != 0) /* parent */ exit(0); setsid();
/* * Change the current working directory to the root so * we won't prevent file systems from being unmounted. */ if (chdir("/") < 0) { fprintf(stderr, "%s: can't change dir to /: %s\n", cmd, (char *)strerror(errno)); exit(-1); }
/* * Close all open file descriptors. */ if (rl.rlim_max == RLIM_INFINITY) rl.rlim_max = 1024; for (i = 0; i < rl.rlim_max; i++) close(i);