Skip to content

Instantly share code, notes, and snippets.

@chaozh
Created January 8, 2013 12:15
Show Gist options
  • Select an option

  • Save chaozh/4483302 to your computer and use it in GitHub Desktop.

Select an option

Save chaozh/4483302 to your computer and use it in GitHub Desktop.
From book Advanced programming in the Unix Environment Charpter 13.4
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <syslog.h>
#include <fcntl.h>
#include <sys/stat.h>
void daemonize(const char* cmd){
int i, fd0, fd1, fd2;
pid_t pid;
struct sigaction sa;
//clear file creation mask
umask(0);
if ((pid = fork()) < 0) {
printf("%s: can't fork\n", cmd);
exit(1);
}
else if(pid != 0) {//parent
exit(0);
}
setsid();
sa.sa_handler = SIG_IGN;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction(SIGHUP, &sa, NULL) < 0) {
printf("%s: can't ignore SIGHUP\n", cmd);
exit(1);
}
if ((pid = fork()) < 0) {
printf("%s: can't fork\n", cmd);
exit(1);
}
else if(pid != 0) {//parent
exit(0);
}
//change current working dir to root
if (chdir("/") < 0) {
printf("%s: can't change dir to /\n", cmd);
exit(1);
}
//close all open file descriptions
if(rl.rlim_max == RLIM_INFINITY)
rl.rlim_max = 1024;
for(i = 0; i < rl.rlim_max; i++)
close(i);
//attach file descriptions 0, 1, 2 to /dev/null
fd0 = open("/dev/null", O_RDWR);
fd1 = dup(0);
fd2 = dup(0);
//initialize the log file
openlog(cmd, LOG_CONS, LOG_DAEMON);
if (fd0 != 0 || fd1 != 0 || fd2 != 0){
syslog(LOG_ERR, "unexpected file descriptions %d %d %d", fd0, fd1, fd2);
exit(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment