#include <unistd.h>
#include <fcntl.h>

/* taken from dietlibc */
int daemonize(void) {
  int fd;
  switch (fork()) {
    case -1: return -1;
    case 0: break;
    default: _exit(0);
  }
  if (setsid()==-1)
    return -1;
  chdir("/");
  fd = open("/dev/null",O_RDWR);
  if (fd==-1)
    return -1;
  dup2(fd,0);
  dup2(fd,1);
  dup2(fd,2);
  if (fd>2)
    close(fd);
  return 0;
}


syntax highlighted by Code2HTML, v. 0.9.1