C/Daemonize

From Attie's Wiki
Revision as of 17:06, 15 March 2012 by Attie (Talk | contribs)

Jump to: navigation, search
int pipefd[2];
 
int daemonize(void) {
  int i;
 
  if (pipe(pipefd) == -1) {
    perror("pipe()");
    return 1;
  }
 
  i = fork();
  if (i < 0) {
    perror("fork()");
    return 1;
  }
  if (i > 0) {
    char c;
    close(pipefd[1]);
    close(fileno(stdin)); /* prevent the parent from stealing the input */
    if (read(pipefd[0],&c,1) <= 0) {
      printf("An error occured, unable to determine if started successfully...\n");
      exit(1);
    }
    if (c) {
      printf("An error occured while starting...\n");
      exit(1);
    }
    printf("Started successfully!\n");
    exit(0);
  }
 
  close(pipefd[0]);
 
  if (setsid() < 0) {
    perror("setsid()");
    return 1;
  }
 
  umask(0);
 
  if ((chdir("/")) < 0) {
    perror("chdir()");
    return 1;
  }
 
  return 0;
}
 
void daemonize_success(void) {
  int i;
 
  i = open("/dev/null",O_RDWR);
  if (i < 0) {
    close(fileno(stderr));
    close(fileno(stdout));
    close(fileno(stdin));
  } else {
    dup2(i,fileno(stderr)); /* 2 = stderr */
    dup2(i,fileno(stdout)); /* 1 = stdout */
    dup2(i,fileno(stdin));  /* 0 = stdin */
    close(i);
  }
 
  i = 0;
  write(pipefd[1],&i,1);
  close(pipefd[1]);
}
 
void daemonize_failure(void) {
  int i;
  i = 1;
  write(pipefd[1],&i,1);
  close(pipefd[1]);
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox