1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
#include <ngx_config.h>
#include <ngx_core.h>
void testone(ngx_log_t *log)
{
ngx_log_debug(log, "child process");
ngx_msleep(5000);
exit(0);
}
int ngx_spawn_process(ngx_log_t *log)
{
pid_t pid;
sigset_t set, oset;
sigemptyset(&set);
sigaddset(&set, SIGCHLD);
if (sigprocmask(SIG_BLOCK, &set, &oset) == -1) {
ngx_log_error(NGX_LOG_ALERT, log, ngx_errno, "sigprocmask() failed");
}
pid = fork();
if (pid == -1 || pid == 0) {
if (sigprocmask(SIG_SETMASK, &oset, &set) == -1) {
ngx_log_error(NGX_LOG_ALERT, log, ngx_errno,
"sigprocmask() failed");
}
}
switch (pid) {
case -1:
ngx_log_error(NGX_LOG_ALERT, log, ngx_errno, "fork() failed");
return NGX_ERROR;
case 0:
testone(log);
break;
default:
break;
}
ngx_log_debug(log, "parent process, child: " PID_T_FMT _ pid);
/* book keeping */
if (sigprocmask(SIG_SETMASK, &oset, &set) == -1) {
ngx_log_error(NGX_LOG_ALERT, log, ngx_errno, "sigprocmask() failed");
}
return NGX_OK;
}
void ngx_sigchld_handler(int signo)
{
int status, one;
pid_t pid;
ngx_err_t err;
struct timeval tv;
ngx_gettimeofday(&tv);
if (ngx_cached_time != tv.tv_sec) {
ngx_cached_time = tv.tv_sec;
ngx_time_update();
}
one = 0;
for ( ;; ) {
pid = waitpid(-1, &status, WNOHANG);
if (pid == 0) {
return;
}
if (pid == -1) {
err = ngx_errno;
if (err == NGX_EINTR) {
continue;
}
if (err == NGX_ECHILD && one) {
return;
}
ngx_log_error(NGX_LOG_ALERT, ngx_cycle->log, errno,
"waitpid() failed");
return;
}
one = 1;
ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0,
"process " PID_T_FMT " exited with code %d", pid, status);
/* TODO: restart handler */
#if 0
ngx_msleep(2000);
#endif
#if 0
ngx_spawn_process(ngx_cycle->log);
#endif
}
}
|