00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034 #include <config.h>
00035
00036 #if defined __SUNPRO_C || defined __DECC || defined __HP_cc
00037 # pragma ident "@(#)$Header: /cvsroot/wikipedia/willow/src/bin/willow/daemon.c,v 1.1 2005/05/02 19:15:21 kateturner Exp $"
00038 # pragma ident "$NetBSD: daemon.c,v 1.9 2003/08/07 16:42:46 agc Exp $"
00039 #endif
00040
00041 #include <fcntl.h>
00042 #include <stdio.h>
00043 #include <stdlib.h>
00044 #include <sys/types.h>
00045 #include <sys/wait.h>
00046 #include <signal.h>
00047 #include <unistd.h>
00048 #include <sys/select.h>
00049
00050 #include <drizzled/daemon.h>
00051
00052 namespace drizzled
00053 {
00054
00055 pid_t parent_pid;
00056
00057 extern "C"
00058 {
00059
00060 static void sigusr1_handler(int sig)
00061 {
00062 if (sig == SIGUSR1)
00063 _exit(EXIT_SUCCESS);
00064 }
00065
00066 }
00067
00068 void daemon_is_ready()
00069 {
00070 kill(parent_pid, SIGUSR1);
00071 }
00072
00073 bool daemonize(bool nochdir, bool noclose, bool wait_sigusr1)
00074 {
00075 int fd;
00076 pid_t child= -1;
00077
00078 parent_pid= getpid();
00079 signal(SIGUSR1, sigusr1_handler);
00080
00081 child= fork();
00082
00083 switch (child)
00084 {
00085 case -1:
00086 return true;
00087 case 0:
00088 break;
00089 default:
00090 if (wait_sigusr1)
00091 {
00092
00093 int exit_code= -1;
00094 int status;
00095 while (waitpid(child, &status, 0) != child)
00096 { }
00097
00098 if (WIFEXITED(status))
00099 {
00100 exit_code= WEXITSTATUS(status);
00101 }
00102 if (WIFSIGNALED(status))
00103 {
00104 exit_code= -1;
00105 }
00106 _exit(exit_code);
00107 }
00108 else
00109 {
00110 _exit(EXIT_SUCCESS);
00111 }
00112 }
00113
00114
00115 if (setsid() == -1)
00116 return true;
00117
00118 if (nochdir == 0) {
00119 if(chdir("/") != 0) {
00120 perror("chdir");
00121 return true;
00122 }
00123 }
00124
00125 if (noclose == 0 && (fd = open("/dev/null", O_RDWR, 0)) != -1) {
00126 if(dup2(fd, STDIN_FILENO) < 0) {
00127 perror("dup2 stdin");
00128 return true;
00129 }
00130 if(dup2(fd, STDOUT_FILENO) < 0) {
00131 perror("dup2 stdout");
00132 return true;
00133 }
00134 if(dup2(fd, STDERR_FILENO) < 0) {
00135 perror("dup2 stderr");
00136 return true;
00137 }
00138
00139 if (fd > STDERR_FILENO) {
00140 if(close(fd) < 0) {
00141 perror("close");
00142 return true;
00143 }
00144 }
00145 }
00146 return false;
00147 }
00148
00149 }