Project

General

Profile

Bug #2712 » daemonize_startup_behaviour_v2.diff

pasdVn, 2016-02-10 17:56

View differences:

src/server.c (working copy)
145 145
#endif
146 146

  
147 147
#ifdef HAVE_FORK
148
static void daemonize(void) {
148
static int daemonize() {
149
	int pipefd[2];
150
	pid_t pid;
149 151
#ifdef SIGTTOU
150 152
	signal(SIGTTOU, SIG_IGN);
151 153
#endif
......
155 157
#ifdef SIGTSTP
156 158
	signal(SIGTSTP, SIG_IGN);
157 159
#endif
158
	if (0 != fork()) exit(0);
159 160

  
161
	if (pipe(pipefd) < 0) exit(-1);
162
		
163
	if (0 > (pid = fork())) exit(-1);
164
	else if (0 < pid)
165
	{
166
		char buf;
167
		ssize_t bytes;
168

  
169
		close(pipefd[1]);
170
		/* parent waits for grandchild to be ready */
171
		bytes = read(pipefd[0], &buf, sizeof(buf));
172
		close(pipefd[0]);
173

  
174
		/* closed fd (without writing) == failure in grandchild */
175
		exit((bytes > 0) ? 0 : -1);
176

  
177
		return 0; /* never reached */
178
	}
179

  
180
	close(pipefd[0]);
181

  
182
	/* better to return -1 in the following error cases? */
160 183
	if (-1 == setsid()) exit(0);
161 184

  
162 185
	signal(SIGHUP, SIG_IGN);
......
164 187
	if (0 != fork()) exit(0);
165 188

  
166 189
	if (0 != chdir("/")) exit(0);
190

  
191
	return pipefd[1];
167 192
}
168 193
#endif
169 194

  
......
568 593
	interval.it_value.tv_usec = 0;
569 594
#endif
570 595

  
596
#ifdef HAVE_FORK
597
	int parent_pipe_fd = 0;
598
#endif
571 599

  
572 600
	/* for nice %b handling in strfime() */
573 601
	setlocale(LC_TIME, "C");
......
951 979

  
952 980
#ifdef HAVE_FORK
953 981
	/* network is up, let's deamonize ourself */
954
	if (srv->srvconf.dont_daemonize == 0) daemonize();
982
	if (srv->srvconf.dont_daemonize == 0) {
983
		parent_pipe_fd = daemonize();
984
	}
955 985
#endif
956 986

  
957 987

  
......
1076 1106
		return -1;
1077 1107
	}
1078 1108

  
1079

  
1109
	
1080 1110
#ifdef HAVE_FORK
1111
	/**
1112
	 * notify daemonize-grandparent of successfull startup
1113
	 * do this before any further forking is done (workers)
1114
	 */
1115
	if (srv->srvconf.dont_daemonize == 0) {
1116
		if (0 > write(parent_pipe_fd, "\x0", 1)) return -1;
1117
		close(parent_pipe_fd);
1118
	}
1119
	
1081 1120
	/* start watcher and workers */
1082 1121
	num_childs = srv->srvconf.max_worker;
1083 1122
	if (num_childs > 0) {
(2-2/2)