! * \brief daemon init * \param name daemon name * \param own_pgid daemon process group * \return return 0 on success, -1 on error */
| 205 | * \return return 0 on success, -1 on error |
| 206 | */ |
| 207 | int daemonize(char* name, int * own_pgid) |
| 208 | { |
| 209 | FILE *pid_stream = NULL; |
| 210 | pid_t pid; |
| 211 | int r, p,rc; |
| 212 | int pid_items; |
| 213 | |
| 214 | p=-1; |
| 215 | |
| 216 | if ( (startup_wdir=getcwd(NULL,0))==NULL) { |
| 217 | LM_ERR("failed to determin the working dir %d/%s\n", errno, |
| 218 | strerror(errno)); |
| 219 | goto error; |
| 220 | } |
| 221 | |
| 222 | /* flush std file descriptors to avoid flushes after fork |
| 223 | * (same message appearing multiple times) |
| 224 | * and switch to unbuffered |
| 225 | */ |
| 226 | setbuf(stdout, 0); |
| 227 | setbuf(stderr, 0); |
| 228 | if (chroot_dir&&(chroot(chroot_dir)<0)){ |
| 229 | LM_CRIT("Cannot chroot to %s: %s\n", chroot_dir, strerror(errno)); |
| 230 | goto error; |
| 231 | } |
| 232 | |
| 233 | if (chdir(working_dir)<0){ |
| 234 | LM_CRIT("Cannot chdir to %s: %s\n", working_dir, strerror(errno)); |
| 235 | goto error; |
| 236 | } |
| 237 | |
| 238 | if (!no_daemon_mode) { |
| 239 | /* fork to become!= group leader*/ |
| 240 | if ((pid=fork())<0){ |
| 241 | LM_CRIT("Cannot fork:%s\n", strerror(errno)); |
| 242 | goto error; |
| 243 | }else if (pid!=0){ |
| 244 | /* parent process => wait for status codes from children*/ |
| 245 | clean_write_pipeend(); |
| 246 | LM_DBG("waiting for status code from children\n"); |
| 247 | rc = wait_for_all_children(); |
| 248 | LM_INFO("pre-daemon process exiting with %d\n",rc); |
| 249 | exit(rc); |
| 250 | } |
| 251 | |
| 252 | /* cleanup read end - nobody should |
| 253 | * need to read from status pipe from this point on */ |
| 254 | clean_read_pipeend(); |
| 255 | |
| 256 | /* become session leader to drop the ctrl. terminal */ |
| 257 | if (setsid()<0){ |
| 258 | LM_WARN("setsid failed: %s\n",strerror(errno)); |
| 259 | }else{ |
| 260 | *own_pgid=1;/* we have our own process group */ |
| 261 | } |
| 262 | /* fork again to drop group leadership */ |
| 263 | if ((pid=fork())<0){ |
| 264 | LM_CRIT("Cannot fork: %s\n", strerror(errno)); |
no test coverage detected