以前写的demo
#define DEV_NULL "/dev/null"
#define ROOT_PATH "/"
int redirect_fd(int fd, int flags) {
/* Attempt to open bit bucket */
int new_fd = open(DEV_NULL, flags);
if (new_fd < 0)
return 1;
/* If descriptor is different, redirect old to new and close new */
if (new_fd != fd) {
dup2(new_fd, fd);
close(new_fd);
}
return 0;
}
int daemonize() {
pid_t pid;
/* Fork once to ensure we aren't the process group leader */
pid = fork();
if (pid < 0) {
return 1;
}
/* Exit if we are the parent */
if (pid > 0) {
_exit(0);
}
/* Start a new session (if not already group leader) */
setsid();
/* Fork again so the session group leader exits */
pid = fork();
if (pid < 0) {
printf("Could not fork() group leader: %s", strerror(errno));
return 1;
}
/* Exit if we are the parent */
if (pid > 0) {
printf("Exiting and passing control to PID %i", pid);
_exit(0);
}
/* Change to root directory */
if (chdir(ROOT_PATH) < 0) {
printf(
"Unable to change working directory to "
ROOT_PATH);
return 1;
}
/* Reopen the 3 stdxxx to /dev/null */
if (redirect_fd(STDIN_FILENO, O_RDONLY)
|| redirect_fd(STDOUT_FILENO, O_WRONLY)
|| redirect_fd(STDERR_FILENO, O_WRONLY)) {
printf(
"Unable to redirect standard file descriptors to "
DEV_NULL);
return 1;
}
/* Success */
return 0;
}