LIBSSDP
 All Classes Files Functions Variables Typedefs Macros
daemon.c
Go to the documentation of this file.
1 
7 #include <stdlib.h>
8 #include <signal.h>
9 #include <sys/stat.h>
10 #include <sys/types.h>
11 #include <unistd.h>
12 
13 #if defined BSD || defined __APPLE__
14 #include <fcntl.h>
15 #include <sys/ioctl.h>
16 #endif
17 
18 #include "common_definitions.h"
19 #include "log.h"
20 
21 void daemonize() {
22 
23  PRINT_DEBUG("Daemonizing...");
24 
25  int fd, max_open_fds;
26 
42  /* If started with init then no need to detach and do all the stuff */
43  if(getppid() == 1) {
44  PRINT_DEBUG("Started by init, skipping some daemon setup");
45  goto started_with_init;
46  }
47 
48  /* Ignore signals */
49  #ifdef SIGTTOU
50  signal(SIGTTOU, SIG_IGN);
51  #endif
52 
53  #ifdef SIGTTIN
54  signal(SIGTTIN, SIG_IGN);
55  #endif
56 
57  #ifdef SIGTSTP
58  signal(SIGTSTP, SIG_IGN);
59  #endif
60 
61  /* Get new PGID (not PG-leader and not zero) and free parent process
62  so terminal can be used/closed */
63  printf("forking...\n");
64  if(fork() != 0) {
65 
66  /* Exit parent */
67  exit(EXIT_SUCCESS);
68 
69  }
70 
71  #if defined BSD || defined __APPLE__
72  PRINT_DEBUG("Using BSD daemon proccess");
73  setpgrp();
74 
75  if((fd = open("/dev/tty", O_RDWR)) >= 0) {
76 
77  /* Get rid of the controlling terminal */
78  ioctl(fd, TIOCNOTTY, 0);
79  close(fd);
80 
81  }
82  else {
83 
84  PRINT_ERROR("Could not dissassociate from controlling terminal: openning /dev/tty failed.");
85  exit(EXIT_FAILURE);
86  }
87  #else
88  PRINT_DEBUG("Using UNIX daemon proccess");
89 
90  /* Non-BSD UNIX systems do the above with a single call to setpgrp() */
91  setpgrp();
92 
93  /* Ignore death if parent dies */
94  signal(SIGHUP,SIG_IGN);
95 
96  /* Get new PGID (not PG-leader and not zero)
97  because non-BSD systems don't allow assigning
98  controlling terminals to non-PG-leader processes */
99  pid_t pid = fork();
100  if(pid < 0) {
101 
102  /* Exit the both processess */
103  exit(EXIT_FAILURE);
104 
105  }
106 
107  if(pid > 0) {
108 
109  /* Exit the parent */
110  exit(EXIT_SUCCESS);
111 
112  }
113  #endif
114 
115  started_with_init:
116 
117  /* Close all possibly open descriptors */
118  PRINT_DEBUG("Closing all open descriptors");
119  max_open_fds = sysconf(_SC_OPEN_MAX);
120  for(fd = 0; fd < max_open_fds; fd++) {
121 
122  close(fd);
123 
124  }
125 
126  /* Change cwd in case it was on a mounted system */
127  if(-1 == chdir("/")) {
128  PRINT_ERROR("Failed to change to a safe directory");
129  exit(EXIT_FAILURE);
130  }
131 
132  /* Clear filemode creation mask */
133  umask(0);
134 
135  PRINT_DEBUG("Now running in daemon mode");
136 
137 }
138 
void daemonize()
Definition: daemon.c:21