C/Daemonize

From Attie's Wiki
(Difference between revisions)
Jump to: navigation, search
m (Created page with '<source lang="c"> int pipefd[2]; int daemonize(void) { int i; if (pipe(pipefd) == -1) { perror("pipe()"); return 1; } i = fork(); if (i < 0) { perror("fo…')
 
m
Line 65: Line 65:
 
   close(pipefd[0]);
 
   close(pipefd[0]);
 
   close(pipefd[1]);
 
   close(pipefd[1]);
 
 
}
 
}
 
</source>
 
</source>

Revision as of 12:48, 11 October 2011

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;
    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);
  }
 
  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); 
  dup2(i,0); /* 0 = stdin */
  dup2(i,1); /* 1 = stdout */
  dup2(i,2); /* 2 = stderr */
  close(i);
 
  i = 0;
  write(pipefd[1],&i,1);
  close(pipefd[0]);
  close(pipefd[1]);
}
 
void daemonize_failure(void) {
  int i;
  i = 1;
  write(pipefd[1],&i,1);
  close(pipefd[0]);
  close(pipefd[1]);
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox