C/Daemonize

From Attie's Wiki
(Difference between revisions)
Jump to: navigation, search
m
m
Line 17: Line 17:
 
   if (i > 0) {
 
   if (i > 0) {
 
     char c;
 
     char c;
 +
    close(pipefd[1]);
 +
    close(fileno(stdin)); /* prevent the parent from stealing the input */
 
     if (read(pipefd[0],&c,1) <= 0) {
 
     if (read(pipefd[0],&c,1) <= 0) {
 
       printf("An error occured, unable to determine if started successfully...\n");
 
       printf("An error occured, unable to determine if started successfully...\n");
Line 28: Line 30:
 
     exit(0);
 
     exit(0);
 
   }
 
   }
 +
 +
  close(pipefd[0]);
 
    
 
    
 
   if (setsid() < 0) {
 
   if (setsid() < 0) {
Line 47: Line 51:
 
   int i;
 
   int i;
  
   i = open("/dev/null",O_RDWR);  
+
   i = open("/dev/null",O_RDWR);
   dup2(i,0); /* 0 = stdin */
+
   if (i < 0) {
  dup2(i,1); /* 1 = stdout */
+
    close(fileno(stderr));
  dup2(i,2); /* 2 = stderr */
+
    close(fileno(stdout));
  close(i);
+
    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;
 
   i = 0;
 
   write(pipefd[1],&i,1);
 
   write(pipefd[1],&i,1);
  close(pipefd[0]);
 
 
   close(pipefd[1]);
 
   close(pipefd[1]);
 
}
 
}
Line 63: Line 72:
 
   i = 1;
 
   i = 1;
 
   write(pipefd[1],&i,1);
 
   write(pipefd[1],&i,1);
  close(pipefd[0]);
 
 
   close(pipefd[1]);
 
   close(pipefd[1]);
 
}
 
}
 
</source>
 
</source>

Revision as of 17:06, 15 March 2012

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