daemon_init.c

Go to the documentation of this file.
00001 
00007 /* $Id: daemon_init.c,v 1.11 2008/12/10 19:02:24 seymour Exp $ */              
00008 /* $UTK_Copyright: $ */
00009 
00010 #include <stdlib.h>
00011 #include <stdio.h>
00012 #include <sys/types.h>
00013 #include <sys/stat.h>
00014 #include <fcntl.h>
00015 
00016 #include "portability.h"
00017 #include "utility.h"
00018 
00034 int 
00035 gs_daemon_init(char *root, char *logfile) {
00036   pid_t pid;
00037   int fd;
00038 
00039   if(!root || !logfile)
00040     return -1;
00041 
00042   pid = fork();
00043 
00044   if(pid < 0)
00045     return -1;
00046 
00047   if(pid != 0) /* parent exits */
00048     exit(0);
00049 
00050   setsid();   /* become session leader */
00051 
00052   pid = fork();
00053 
00054   if(pid < 0)
00055     return -1;
00056 
00057   if(pid != 0) /* 1st child exits */
00058     exit(0);
00059 
00060   if(chdir(root) < 0) {
00061     perror("chdir()");
00062     return -1;
00063   }
00064   umask(0);
00065 
00066   /* Remap stdin to /dev/null */
00067   fd = open("/dev/null", O_RDWR|O_CREAT, 0644);
00068   if(fd < 0) {
00069     perror("open()");
00070     return -1;
00071   }
00072   close(0);
00073   if(dup2(fd, 0) < 0) {
00074     ERRPRINTF("dup2 failed\n");
00075     perror("dup2()");
00076     return -1;
00077   }
00078   close(fd);
00079 
00080   fprintf(stderr, "\n"
00081     "==============================================================\n"
00082     "|       -- Giving up terminal control! --\n|\n"
00083     "| All further terminal output will be sent to the log file:\n"
00084     "|\t\"%s\"\n"
00085     "=============================================================="
00086     "\n\n", logfile);
00087 
00088   /* Open logfile */
00089   remove(logfile);
00090   fd = open(logfile, O_RDWR|O_CREAT, 0644);
00091   if(fd < 0){
00092     ERRPRINTF("open failed\n");
00093     perror("open()");
00094     return -1;
00095   }
00096 
00097   /* Remap stdout and stderr to logfile */
00098   close(1);
00099   if(dup2(fd, 1) < 0){
00100     ERRPRINTF("dup2 failed\n");
00101     perror("dup2()");
00102     return -1;
00103   }
00104   close(2);
00105   if(dup2(fd, 2) < 0){
00106     ERRPRINTF("dup2 failed\n");
00107     perror("dup2()");
00108     return -1;
00109   }
00110   close(fd);
00111 
00112   return 0;
00113 }