<commit_before>// annotated by chrono since 2016
//
// * ngx_master_process_cycle
// * ngx_single_process_cycle
// * ngx_worker_process_cycle
// * ngx_signal_worker_processes
// * ngx_worker_process_init
// * ngx_reap_children

/*
 * Copyright (C) <NAME>
 * Copyright (C) Nginx, Inc.
 */


#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_event.h>
#include <ngx_channel.h>


// 被ngx_master_process_cycle()调用
// 启动worker进程，数量由配置决定，即worker_processes指令
// 调用时传递的是#define NGX_PROCESS_RESPAWN       -3
static void ngx_start_worker_processes(ngx_cycle_t *cycle, ngx_int_t n,
    ngx_int_t type);

// cache相关的暂不研究
static void ngx_start_cache_manager_processes(ngx_cycle_t *cycle,
    ngx_uint_t respawn);

static void ngx_pass_open_channel(ngx_cycle_t *cycle, ngx_channel_t *ch);

// master进程调用，遍历ngx_processes数组，用kill发送信号
static void ngx_signal_worker_processes(ngx_cycle_t *cycle, int signo);

// 重新产生子进程
static ngx_uint_t ngx_reap_children(ngx_cycle_t *cycle);

// 删除pid，模块清理，关闭监听端口
static void ngx_master_process_exit(ngx_cycle_t *cycle);

// 传递给ngx_spawn_process()，是worker进程的核心功能
// 调用ngx_worker_process_init()/ngx_worker_process_exit()
static void ngx_worker_process_cycle(ngx_cycle_t *cycle, void *data);

// 读取核心配置，设置cpu优先级,core dump信息,unix运行的group/user
// 切换工作路径,根据pid设置随机数种子
// 调用所有模块的init_process,让模块进程初始化
static void ngx_worker_process_init(ngx_cycle_t *cycle, ngx_int_t worker);

// 被ngx_worker_process_cycle()调用
// 调用所有模块的exit_process，进程结束hook
// 内部直接exit(0)退出
static void ngx_worker_process_exit(ngx_cycle_t *cycle);

// cache相关的暂不研究
static void ngx_channel_handler(ngx_event_t *ev);
static void ngx_cache_manager_process_cycle(ngx_cycle_t *cycle, void *data);
static void ngx_cache_manager_process_handler(ngx_event_t *ev);
static void ngx_cache_loader_process_handler(ngx_event_t *ev);


// 标记nginx进程的状态
// NGX_PROCESS_MASTER/NGX_PROCESS_WORKER/NGX_PROCESS_SINGLE
// 一开始是0，也就是NGX_PROCESS_SINGLE
ngx_uint_t    ngx_process;

// nginx 1.9.x增加新全局变量ngx_worker，即进程id号
// 从0开始计数，至ccf->worker_processes
ngx_uint_t    ngx_worker;

// 记录master/worker进程的pid
// master在main()里获取
// worker在fork之后重新获取
ngx_pid_t     ngx_pid;

// 1.13.8，父进程的pid
// worker在fork之后重新获取
ngx_pid_t     ngx_parent;

// 原子变量，用于进程中检查信号
sig_atomic_t  ngx_reap;
sig_atomic_t  ngx_sigio;
sig_atomic_t  ngx_sigalrm;      //更新时间的信号
sig_atomic_t  ngx_terminate;    //结束进程
sig_atomic_t  ngx_quit;         //处理完所有请求再结束进程
sig_atomic_t  ngx_debug_quit;
ngx_uint_t    ngx_exiting;      //nginx进程正在退出过程中
sig_atomic_t  ngx_reconfigure;  //重新加载配置文件，也就是reload
sig_atomic_t  ngx_reopen;       //重新打开所有文件

sig_atomic_t  ngx_change_binary;
ngx_pid_t     ngx_new_binary;
ngx_uint_t    ngx_inherited;
ngx_uint_t    ngx_daemonized;

sig_atomic_t  ngx_noaccept;
ngx_uint_t    ngx_noaccepting;
ngx_uint_t    ngx_restart;


// master进程的名字
static u_char  master_process[] = "master process";


static ngx_cache_manager_ctx_t  ngx_cache_manager_ctx = {
    ngx_cache_manager_process_handler, "cache manager process", 0
};

static ngx_cache_manager_ctx_t  ngx_cache_loader_ctx = {
    ngx_cache_loader_process_handler, "cache loader process", 60000
};


static ngx_cycle_t      ngx_exit_cycle;
static ngx_log_t        ngx_exit_log;
static ngx_open_file_t  ngx_exit_log_file;


// main()函数里调用，启动worker进程
// 监听信号
// 核心操作是sigsuspend，暂时挂起进程，不占用CPU，只有收到信号时才被唤醒
void
ngx_master_process_cycle(ngx_cycle_t *cycle)
{
    char              *title;
    u_char            *p;
    size_t             size;
    ngx_int_t          i;
    ngx_uint_t         n, sigio;
    sigset_t           set;
    struct itimerval   itv;
    ngx_uint_t         live;
    ngx_msec_t         delay;
    ngx_listening_t   *ls;
    ngx_core_conf_t   *ccf;

    // 添加master进程关注的信号
    sigemptyset(&set);
    sigaddset(&set, SIGCHLD);
    sigaddset(&set, SIGALRM);
    sigaddset(&set, SIGIO);
    sigaddset(&set, SIGINT);
    sigaddset(&set, ngx_signal_value(NGX_RECONFIGURE_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_REOPEN_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_NOACCEPT_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_TERMINATE_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_SHUTDOWN_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_CHANGEBIN_SIGNAL));

    if (sigprocmask(SIG_BLOCK, &set, NULL) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "sigprocmask() failed");
    }

    sigemptyset(&set);


    // static u_char  master_process[] = "master process";
    // 计算master进程的名字
    size = sizeof(master_process);

    // 加上命令行参数，注意使用的是nginx拷贝后的参数
    for (i = 0; i < ngx_argc; i++) {
        size += ngx_strlen(ngx_argv[i]) + 1;
    }

    // 分配名字的内存
    title = ngx_pnalloc(cycle->pool, size);
    if (title == NULL) {
        /* fatal */
        exit(2);
    }

    // 拷贝字符串
    p = ngx_cpymem(title, master_process, sizeof(master_process) - 1);
    for (i = 0; i < ngx_argc; i++) {
        *p++ = ' ';
        p = ngx_cpystrn(p, (u_char *) ngx_argv[i], size);
    }

    // 设置进程名
    ngx_setproctitle(title);


    // 取core模块配置
    ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);

    // 启动worker进程，数量由配置决定，即worker_processes指令
    // #define NGX_PROCESS_RESPAWN       -3
    ngx_start_worker_processes(cycle, ccf->worker_processes,
                               NGX_PROCESS_RESPAWN);

    // cache进程
    ngx_start_cache_manager_processes(cycle, 0);

    ngx_new_binary = 0;
    delay = 0;      //延时的计数器
    sigio = 0;
    live = 1;       //是否有存活的子进程

    // master进程的无限循环，只处理信号
    // 主要调用ngx_signal_worker_processes()发送信号
    // ngx_start_worker_processes()产生新子进程
    for ( ;; ) {
        // 延时等待子进程关闭，每次进入加倍等待
        if (delay) {
            if (ngx_sigalrm) {
                sigio = 0;
                delay *= 2;     //延时加倍
                ngx_sigalrm = 0;
            }

            ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0,
                           "termination cycle: %M", delay);

            itv.it_interval.tv_sec = 0;
            itv.it_interval.tv_usec = 0;
            itv.it_value.tv_sec = delay / 1000;
            itv.it_value.tv_usec = (delay % 1000 ) * 1000;

            // 系统调用，设置发送SIGALRM的时间间隔
            if (setitimer(ITIMER_REAL, &itv, NULL) == -1) {
                ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                              "setitimer() failed");
            }
        }

        ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "sigsuspend");

        // 核心操作是sigsuspend，暂时挂起进程，不占用CPU，只有收到信号时才被唤醒
        // 收到SIGALRM就检查子进程是否都已经处理完了
        sigsuspend(&set);

        // 更新一下时间
        ngx_time_update();

        ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0,
                       "wake up, sigio %i", sigio);

        // 子进程可能发生了意外结束
        // 在os/unix/ngx_process.c ngx_signal_handler()里设置
        if (ngx_reap) {
            ngx_reap = 0;
            ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "reap children");

            // 重新产生子进程
            live = ngx_reap_children(cycle);
        }

        // 无存活子进程且收到stop/quit信号
        if (!live && (ngx_terminate || ngx_quit)) {
            // 删除pid，模块清理，关闭监听端口
            // 内部直接exit(0)退出
            ngx_master_process_exit(cycle);
        }

        // 收到了-s stop，停止进程
        if (ngx_terminate) {
            // 延时等待子进程关闭
            if (delay == 0) {
                delay = 50;
            }

            if (sigio) {
                sigio--;
                continue;
            }

            sigio = ccf->worker_processes + 2 /* cache processes */;

            if (delay > 1000) {
                // 超时太多，直接发送SIGKILL杀死进程
                // master进程调用，遍历ngx_processes数组，用kill发送信号
                ngx_signal_worker_processes(cycle, SIGKILL);
            } else {
                // master进程调用，遍历ngx_processes数组，用kill发送信号
                // 走到worker进程的ngx_signal_handler()
                // 然后再是ngx_worker_process_cycle()的ngx_terminate
                ngx_signal_worker_processes(cycle,
                                       ngx_signal_value(NGX_TERMINATE_SIGNAL));
            }

            // 等待SIGALRM信号，检查子进程是否都结束
            continue;
        }

        // 收到了-s quit，关闭监听端口后再停止进程（优雅关闭）
        if (ngx_quit) {
            // master进程调用，遍历ngx_processes数组，用kill发送信号
            // 走到worker进程的ngx_signal_handler()
            // 然后再是ngx_worker_process_cycle()的ngx_quit
            ngx_signal_worker_processes(cycle,
                                        ngx_signal_value(NGX_SHUTDOWN_SIGNAL));

            // 关闭所有监听端口
            ls = cycle->listening.elts;
            for (n = 0; n < cycle->listening.nelts; n++) {
                if (ngx_close_socket(ls[n].fd) == -1) {
                    ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_socket_errno,
                                  ngx_close_socket_n " %V failed",
                                  &ls[n].addr_text);
                }
            }
            cycle->listening.nelts = 0;

            continue;
        }

        // 收到了-s reload重新配置
        if (ngx_reconfigure) {
            ngx_reconfigure = 0;

            // 启动新的nginx二进制
            if (ngx_new_binary) {
                // 启动worker进程，数量由配置决定，即worker_processes指令
                // 调用时传递的是#define NGX_PROCESS_RESPAWN       -3
                ngx_start_worker_processes(cycle, ccf->worker_processes,
                                           NGX_PROCESS_RESPAWN);
                ngx_start_cache_manager_processes(cycle, 0);
                ngx_noaccepting = 0;

                continue;
            }

            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reconfiguring");

            // nginx可执行程序不变，以当前cycle重新初始化
            cycle = ngx_init_cycle(cycle);
            if (cycle == NULL) {
                cycle = (ngx_cycle_t *) ngx_cycle;
                continue;
            }

            // ngx_cycle指针指向新的cycle
            ngx_cycle = cycle;
            ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx,
                                                   ngx_core_module);

            // 启动worker进程，数量由配置决定，即worker_processes指令
            // 调用时传递的是#define NGX_PROCESS_JUST_RESPAWN       -2
            // 这样新启动的进程不会发送shutdown信号
            ngx_start_worker_processes(cycle, ccf->worker_processes,
                                       NGX_PROCESS_JUST_RESPAWN);
            ngx_start_cache_manager_processes(cycle, 1);

            /* allow new processes to start */
            // 阻塞等待100毫秒
            ngx_msleep(100);

            // 设置进程存活标志
            live = 1;

            // 关闭原来的worker进程
            // 新启动的进程不会发送shutdown信号
            // master进程调用，遍历ngx_processes数组，用kill发送信号
            // 走到worker进程的ngx_signal_handler()
            // 然后再是ngx_worker_process_cycle()的ngx_quit
            ngx_signal_worker_processes(cycle,
                                        ngx_signal_value(NGX_SHUTDOWN_SIGNAL));
        }

        if (ngx_restart) {
            ngx_restart = 0;

            // 启动worker进程，数量由配置决定，即worker_processes指令
            // 调用时传递的是#define NGX_PROCESS_RESPAWN       -3
            ngx_start_worker_processes(cycle, ccf->worker_processes,
                                       NGX_PROCESS_RESPAWN);
            ngx_start_cache_manager_processes(cycle, 0);

            // 设置进程存活标志
            live = 1;
        }

        // sigusr1， 重新打开日志文件，用来rotate日志
        if (ngx_reopen) {
            ngx_reopen = 0;
            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reopening logs");
            ngx_reopen_files(cycle, ccf->user);
            ngx_signal_worker_processes(cycle,
                                        ngx_signal_value(NGX_REOPEN_SIGNAL));
        }

        // 热更新nginx可执行文件
        if (ngx_change_binary) {
            ngx_change_binary = 0;
            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "changing binary");

            // 函数在core/nginx.c里
            ngx_new_binary = ngx_exec_new_binary(cycle, ngx_argv);
        }

        // 停止监听端口
        if (ngx_noaccept) {
            ngx_noaccept = 0;
            ngx_noaccepting = 1;
            ngx_signal_worker_processes(cycle,
                                        ngx_signal_value(NGX_SHUTDOWN_SIGNAL));
        }
    }   //master进程无限循环结束
}


// main()函数里调用，仅启动一个进程，没有fork
// master_process off;
void
ngx_single_process_cycle(ngx_cycle_t *cycle)
{
    ngx_uint_t  i;

    if (ngx_set_environment(cycle, NULL) == NULL) {
        /* fatal */
        exit(2);
    }

    // 调用所有模块的init_process，即进程启动时hook
    for (i = 0; cycle->modules[i]; i++) {
        if (cycle->modules[i]->init_process) {
            if (cycle->modules[i]->init_process(cycle) == NGX_ERROR) {
                /* fatal */
                exit(2);
            }
        }
    }

    // 无限循环，对外提供服务
    // ngx_signal_handler处理unix信号
    // 收到信号后设置ngx_quit/ngx_sigalrm/ngx_reconfigue等全局变量
    // 由无限循环检查这些变量再处理
    for ( ;; ) {
        ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "worker cycle");

        // 处理事件的核心函数, event模块里
        // 处理socket读写事件和定时器事件
        // 获取负载均衡锁，监听端口接受连接
        // 调用epoll模块的ngx_epoll_process_events
        // 然后处理超时事件和在延后队列里的所有事件
        // nginx大部分的工作量都在这里
        ngx_process_events_and_timers(cycle);

        // 检查是否处于退出状态
        // 这里不使用ngx_exiting变量，直接关闭端口退出
        if (ngx_terminate || ngx_quit) {

            // 所有模块的退出hook
            for (i = 0; cycle->modules[i]; i++) {
                if (cycle->modules[i]->exit_process) {
                    cycle->modules[i]->exit_process(cycle);
                }
            }

            // 删除pid，模块清理，关闭监听端口
            // 内部直接exit(0)退出
            ngx_master_process_exit(cycle);
        }

        // 重新配置，以当前cycle重新初始化，即reload
        if (ngx_reconfigure) {
            ngx_reconfigure = 0;    //标志量清零
            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reconfiguring");

            // 以当前cycle重新初始化
            cycle = ngx_init_cycle(cycle);
            if (cycle == NULL) {
                cycle = (ngx_cycle_t *) ngx_cycle;
                continue;
            }

            // ngx_cycle指针指向新的cycle
            ngx_cycle = cycle;
        }

        // 重新打开所有文件
        if (ngx_reopen) {
            ngx_reopen = 0;
            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reopening logs");
            ngx_reopen_files(cycle, (ngx_uid_t) -1);
        }
    } // 无限循环，对外提供服务
}


// 被ngx_master_process_cycle()调用
// 启动worker进程，数量由配置决定，即worker_processes指令
// 调用时传递的是#define NGX_PROCESS_RESPAWN       -3
static void
ngx_start_worker_processes(ngx_cycle_t *cycle, ngx_int_t n, ngx_int_t type)
{
    ngx_int_t      i;
    ngx_channel_t  ch;

    ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "start worker processes");

    ngx_memzero(&ch, sizeof(ngx_channel_t));

    // unix channel
    ch.command = NGX_CMD_OPEN_CHANNEL;

    for (i = 0; i < n; i++) {

        // os/unix/ngx_process.c产生进程，执行ngx_worker_process_cycle
        // 创建的进程都在ngx_processes数组里
        // 定义在os/unix/ngx_process.c
        // ngx_process_t    ngx_processes[NGX_MAX_PROCESSES];
        ngx_spawn_process(cycle, ngx_worker_process_cycle,
                          (void *) (intptr_t) i, "worker process", type);

        // 设置channel信息
        ch.pid = ngx_processes[ngx_process_slot].pid;
        ch.slot = ngx_process_slot;
        ch.fd = ngx_processes[ngx_process_slot].channel[0];

        // 建立channel，用于进程间通信
        ngx_pass_open_channel(cycle, &ch);
    }
}


static void
ngx_start_cache_manager_processes(ngx_cycle_t *cycle, ngx_uint_t respawn)
{
    ngx_uint_t       i, manager, loader;
    ngx_path_t     **path;
    ngx_channel_t    ch;

    manager = 0;
    loader = 0;

    path = ngx_cycle->paths.elts;
    for (i = 0; i < ngx_cycle->paths.nelts; i++) {

        if (path[i]->manager) {
            manager = 1;
        }

        if (path[i]->loader) {
            loader = 1;
        }
    }

    if (manager == 0) {
        return;
    }

    ngx_spawn_process(cycle, ngx_cache_manager_process_cycle,
                      &ngx_cache_manager_ctx, "cache manager process",
                      respawn ? NGX_PROCESS_JUST_RESPAWN : NGX_PROCESS_RESPAWN);

    ngx_memzero(&ch, sizeof(ngx_channel_t));

    ch.command = NGX_CMD_OPEN_CHANNEL;
    ch.pid = ngx_processes[ngx_process_slot].pid;
    ch.slot = ngx_process_slot;
    ch.fd = ngx_processes[ngx_process_slot].channel[0];

    ngx_pass_open_channel(cycle, &ch);

    if (loader == 0) {
        return;
    }

    ngx_spawn_process(cycle, ngx_cache_manager_process_cycle,
                      &ngx_cache_loader_ctx, "cache loader process",
                      respawn ? NGX_PROCESS_JUST_SPAWN : NGX_PROCESS_NORESPAWN);

    ch.command = NGX_CMD_OPEN_CHANNEL;
    ch.pid = ngx_processes[ngx_process_slot].pid;
    ch.slot = ngx_process_slot;
    ch.fd = ngx_processes[ngx_process_slot].channel[0];

    ngx_pass_open_channel(cycle, &ch);
}


static void
ngx_pass_open_channel(ngx_cycle_t *cycle, ngx_channel_t *ch)
{
    ngx_int_t  i;

    for (i = 0; i < ngx_last_process; i++) {

        if (i == ngx_process_slot
            || ngx_processes[i].pid == -1
            || ngx_processes[i].channel[0] == -1)
        {
            continue;
        }

        ngx_log_debug6(NGX_LOG_DEBUG_CORE, cycle->log, 0,
                      "pass channel s:%i pid:%P fd:%d to s:%i pid:%P fd:%d",
                      ch->slot, ch->pid, ch->fd,
                      i, ngx_processes[i].pid,
                      ngx_processes[i].channel[0]);

        /* TODO: NGX_AGAIN */

        ngx_write_channel(ngx_processes[i].channel[0],
                          ch, sizeof(ngx_channel_t), cycle->log);
    }
}


// master进程调用，遍历ngx_processes数组，用kill发送信号
static void
ngx_signal_worker_processes(ngx_cycle_t *cycle, int signo)
{
    ngx_int_t      i;
    ngx_err_t      err;
    ngx_channel_t  ch;

    ngx_memzero(&ch, sizeof(ngx_channel_t));

#if (NGX_BROKEN_SCM_RIGHTS)

    ch.command = 0;

#else

    switch (signo) {

    case ngx_signal_value(NGX_SHUTDOWN_SIGNAL):
        ch.command = NGX_CMD_QUIT;
        break;

    case ngx_signal_value(NGX_TERMINATE_SIGNAL):
        ch.command = NGX_CMD_TERMINATE;
        break;

    case ngx_signal_value(NGX_REOPEN_SIGNAL):
        ch.command = NGX_CMD_REOPEN;
        break;

    default:
        ch.command = 0;
    }

#endif

    ch.fd = -1;


    // 遍历ngx_processes数组，用kill发送信号
    for (i = 0; i < ngx_last_process; i++) {

        ngx_log_debug7(NGX_LOG_DEBUG_EVENT, cycle->log, 0,
                       "child: %i %P e:%d t:%d d:%d r:%d j:%d",
                       i,
                       ngx_processes[i].pid,
                       ngx_processes[i].exiting,
                       ngx_processes[i].exited,
                       ngx_processes[i].detached,
                       ngx_processes[i].respawn,
                       ngx_processes[i].just_spawn);

        if (ngx_processes[i].detached || ngx_processes[i].pid == -1) {
            continue;
        }

        // 新启动的进程不会发送信号
        if (ngx_processes[i].just_spawn) {
            ngx_processes[i].just_spawn = 0;
            continue;
        }

        if (ngx_processes[i].exiting
            && signo == ngx_signal_value(NGX_SHUTDOWN_SIGNAL))
        {
            continue;
        }

        if (ch.command) {
            if (ngx_write_channel(ngx_processes[i].channel[0],
                                  &ch, sizeof(ngx_channel_t), cycle->log)
                == NGX_OK)
            {
                if (signo != ngx_signal_value(NGX_REOPEN_SIGNAL)) {
                    ngx_processes[i].exiting = 1;
                }

                continue;
            }
        }

        ngx_log_debug2(NGX_LOG_DEBUG_CORE, cycle->log, 0,
                       "kill (%P, %d)", ngx_processes[i].pid, signo);

        // kill发送信号
        if (kill(ngx_processes[i].pid, signo) == -1) {
            err = ngx_errno;
            ngx_log_error(NGX_LOG_ALERT, cycle->log, err,
                          "kill(%P, %d) failed", ngx_processes[i].pid, signo);

            if (err == NGX_ESRCH) {<commit_msg>ngx_process_cycle.c<commit_after>// annotated by chrono since 2016
//
// * ngx_master_process_cycle
// * ngx_single_process_cycle
// * ngx_worker_process_cycle
// * ngx_signal_worker_processes
// * ngx_worker_process_init
// * ngx_reap_children

/*
 * Copyright (C) <NAME>
 * Copyright (C) Nginx, Inc.
 */


#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_event.h>
#include <ngx_channel.h>


// 被ngx_master_process_cycle()调用
// 启动worker进程，数量由配置决定，即worker_processes指令
// 调用时传递的是#define NGX_PROCESS_RESPAWN       -3
static void ngx_start_worker_processes(ngx_cycle_t *cycle, ngx_int_t n,
    ngx_int_t type);

// cache相关的暂不研究
static void ngx_start_cache_manager_processes(ngx_cycle_t *cycle,
    ngx_uint_t respawn);

static void ngx_pass_open_channel(ngx_cycle_t *cycle, ngx_channel_t *ch);

// master进程调用，遍历ngx_processes数组，用kill发送信号
static void ngx_signal_worker_processes(ngx_cycle_t *cycle, int signo);

// 重新产生子进程
static ngx_uint_t ngx_reap_children(ngx_cycle_t *cycle);

// 删除pid，模块清理，关闭监听端口
static void ngx_master_process_exit(ngx_cycle_t *cycle);

// 传递给ngx_spawn_process()，是worker进程的核心功能
// 调用ngx_worker_process_init()/ngx_worker_process_exit()
static void ngx_worker_process_cycle(ngx_cycle_t *cycle, void *data);

// 读取核心配置，设置cpu优先级,core dump信息,unix运行的group/user
// 切换工作路径,根据pid设置随机数种子
// 调用所有模块的init_process,让模块进程初始化
static void ngx_worker_process_init(ngx_cycle_t *cycle, ngx_int_t worker);

// 被ngx_worker_process_cycle()调用
// 调用所有模块的exit_process，进程结束hook
// 内部直接exit(0)退出
static void ngx_worker_process_exit(ngx_cycle_t *cycle);

// cache相关的暂不研究
static void ngx_channel_handler(ngx_event_t *ev);
static void ngx_cache_manager_process_cycle(ngx_cycle_t *cycle, void *data);
static void ngx_cache_manager_process_handler(ngx_event_t *ev);
static void ngx_cache_loader_process_handler(ngx_event_t *ev);


// 标记nginx进程的状态
// NGX_PROCESS_MASTER/NGX_PROCESS_WORKER/NGX_PROCESS_SINGLE
// 一开始是0，也就是NGX_PROCESS_SINGLE
ngx_uint_t    ngx_process;

// nginx 1.9.x增加新全局变量ngx_worker，即进程id号
// 从0开始计数，至ccf->worker_processes
ngx_uint_t    ngx_worker;

// 记录master/worker进程的pid
// master在main()里获取
// worker在fork之后重新获取
ngx_pid_t     ngx_pid;

// 1.13.8，父进程的pid
// worker在fork之后重新获取
ngx_pid_t     ngx_parent;

// 原子变量，用于进程中检查信号
sig_atomic_t  ngx_reap;
sig_atomic_t  ngx_sigio;
sig_atomic_t  ngx_sigalrm;      //更新时间的信号
sig_atomic_t  ngx_terminate;    //结束进程
sig_atomic_t  ngx_quit;         //处理完所有请求再结束进程
sig_atomic_t  ngx_debug_quit;
ngx_uint_t    ngx_exiting;      //nginx进程正在退出过程中
sig_atomic_t  ngx_reconfigure;  //重新加载配置文件，也就是reload
sig_atomic_t  ngx_reopen;       //重新打开所有文件

sig_atomic_t  ngx_change_binary;
ngx_pid_t     ngx_new_binary;
ngx_uint_t    ngx_inherited;
ngx_uint_t    ngx_daemonized;

sig_atomic_t  ngx_noaccept;
ngx_uint_t    ngx_noaccepting;
ngx_uint_t    ngx_restart;


// master进程的名字
static u_char  master_process[] = "master process";


static ngx_cache_manager_ctx_t  ngx_cache_manager_ctx = {
    ngx_cache_manager_process_handler, "cache manager process", 0
};

static ngx_cache_manager_ctx_t  ngx_cache_loader_ctx = {
    ngx_cache_loader_process_handler, "cache loader process", 60000
};


static ngx_cycle_t      ngx_exit_cycle;
static ngx_log_t        ngx_exit_log;
static ngx_open_file_t  ngx_exit_log_file;


// main()函数里调用，启动worker进程
// 监听信号
// 核心操作是sigsuspend，暂时挂起进程，不占用CPU，只有收到信号时才被唤醒
void
ngx_master_process_cycle(ngx_cycle_t *cycle)
{
    char              *title;
    u_char            *p;
    size_t             size;
    ngx_int_t          i;
    ngx_uint_t         n, sigio;
    sigset_t           set;
    struct itimerval   itv;
    ngx_uint_t         live;
    ngx_msec_t         delay;
    ngx_listening_t   *ls;
    ngx_core_conf_t   *ccf;

    // 添加master进程关注的信号
    sigemptyset(&set);
    sigaddset(&set, SIGCHLD);
    sigaddset(&set, SIGALRM);
    sigaddset(&set, SIGIO);
    sigaddset(&set, SIGINT);
    sigaddset(&set, ngx_signal_value(NGX_RECONFIGURE_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_REOPEN_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_NOACCEPT_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_TERMINATE_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_SHUTDOWN_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_CHANGEBIN_SIGNAL));

    if (sigprocmask(SIG_BLOCK, &set, NULL) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "sigprocmask() failed");
    }

    sigemptyset(&set);


    // static u_char  master_process[] = "master process";
    // 计算master进程的名字
    size = sizeof(master_process);

    // 加上命令行参数，注意使用的是nginx拷贝后的参数
    for (i = 0; i < ngx_argc; i++) {
        size += ngx_strlen(ngx_argv[i]) + 1;
    }

    // 分配名字的内存
    title = ngx_pnalloc(cycle->pool, size);
    if (title == NULL) {
        /* fatal */
        exit(2);
    }

    // 拷贝字符串
    p = ngx_cpymem(title, master_process, sizeof(master_process) - 1);
    for (i = 0; i < ngx_argc; i++) {
        *p++ = ' ';
        p = ngx_cpystrn(p, (u_char *) ngx_argv[i], size);
    }

    // 设置进程名
    ngx_setproctitle(title);


    // 取core模块配置
    ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);

    // 启动worker进程，数量由配置决定，即worker_processes指令
    // #define NGX_PROCESS_RESPAWN       -3
    ngx_start_worker_processes(cycle, ccf->worker_processes,
                               NGX_PROCESS_RESPAWN);

    // cache进程
    ngx_start_cache_manager_processes(cycle, 0);

    ngx_new_binary = 0;
    delay = 0;      //延时的计数器
    sigio = 0;
    live = 1;       //是否有存活的子进程

    // master进程的无限循环，只处理信号
    // 主要调用ngx_signal_worker_processes()发送信号
    // ngx_start_worker_processes()产生新子进程
    for ( ;; ) {
        // 延时等待子进程关闭，每次进入加倍等待
        if (delay) {
            if (ngx_sigalrm) {
                sigio = 0;
                delay *= 2;     //延时加倍
                ngx_sigalrm = 0;
            }

            ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0,
                           "termination cycle: %M", delay);

            itv.it_interval.tv_sec = 0;
            itv.it_interval.tv_usec = 0;
            itv.it_value.tv_sec = delay / 1000;
            itv.it_value.tv_usec = (delay % 1000 ) * 1000;

            // 系统调用，设置发送SIGALRM的时间间隔
            if (setitimer(ITIMER_REAL, &itv, NULL) == -1) {
                ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                              "setitimer() failed");
            }
        }

        ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "sigsuspend");

        // 核心操作是sigsuspend，暂时挂起进程，不占用CPU，只有收到信号时才被唤醒
        // 收到SIGALRM就检查子进程是否都已经处理完了
        sigsuspend(&set);

        // 更新一下时间
        ngx_time_update();

        ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0,
                       "wake up, sigio %i", sigio);

        // 子进程可能发生了意外结束
        // 在os/unix/ngx_process.c ngx_signal_handler()里设置
        if (ngx_reap) {
            ngx_reap = 0;
            ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "reap children");

            // 重新产生子进程
            live = ngx_reap_children(cycle);
        }

        // 无存活子进程且收到stop/quit信号
        if (!live && (ngx_terminate || ngx_quit)) {
            // 删除pid，模块清理，关闭监听端口
            // 内部直接exit(0)退出
            ngx_master_process_exit(cycle);
        }

        // 收到了-s stop，停止进程
        if (ngx_terminate) {
            // 延时等待子进程关闭
            if (delay == 0) {
                delay = 50;
            }

            if (sigio) {
                sigio--;
                continue;
            }

            sigio = ccf->worker_processes + 2 /* cache processes */;

            if (delay > 1000) {
                // 超时太多，直接发送SIGKILL杀死进程
                // master进程调用，遍历ngx_processes数组，用kill发送信号
                ngx_signal_worker_processes(cycle, SIGKILL);
            } else {
                // master进程调用，遍历ngx_processes数组，用kill发送信号
                // 走到worker进程的ngx_signal_handler()
                // 然后再是ngx_worker_process_cycle()的ngx_terminate
                ngx_signal_worker_processes(cycle,
                                       ngx_signal_value(NGX_TERMINATE_SIGNAL));
            }

            // 等待SIGALRM信号，检查子进程是否都结束
            continue;
        }

        // 收到了-s quit，关闭监听端口后再停止进程（优雅关闭）
        if (ngx_quit) {
            // master进程调用，遍历ngx_processes数组，用kill发送信号
            // 走到worker进程的ngx_signal_handler()
            // 然后再是ngx_worker_process_cycle()的ngx_quit
            ngx_signal_worker_processes(cycle,
                                        ngx_signal_value(NGX_SHUTDOWN_SIGNAL));

            // 关闭所有监听端口
            ls = cycle->listening.elts;
            for (n = 0; n < cycle->listening.nelts; n++) {
                if (ngx_close_socket(ls[n].fd) == -1) {
                    ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_socket_errno,
                                  ngx_close_socket_n " %V failed",
                                  &ls[n].addr_text);
                }
            }
            cycle->listening.nelts = 0;

            continue;
        }

        // 收到了-s reload重新配置
        if (ngx_reconfigure) {
            ngx_reconfigure = 0;

            // 启动新的nginx二进制
            if (ngx_new_binary) {
                // 启动worker进程，数量由配置决定，即worker_processes指令
                // 调用时传递的是#define NGX_PROCESS_RESPAWN       -3
                ngx_start_worker_processes(cycle, ccf->worker_processes,
                                           NGX_PROCESS_RESPAWN);
                ngx_start_cache_manager_processes(cycle, 0);
                ngx_noaccepting = 0;

                continue;
            }

            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reconfiguring");

            // nginx可执行程序不变，以当前cycle重新初始化
            cycle = ngx_init_cycle(cycle);
            if (cycle == NULL) {
                cycle = (ngx_cycle_t *) ngx_cycle;
                continue;
            }

            // ngx_cycle指针指向新的cycle
            ngx_cycle = cycle;
            ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx,
                                                   ngx_core_module);

            // 启动worker进程，数量由配置决定，即worker_processes指令
            // 调用时传递的是#define NGX_PROCESS_JUST_RESPAWN       -2
            // 这样新启动的进程不会发送shutdown信号
            ngx_start_worker_processes(cycle, ccf->worker_processes,
                                       NGX_PROCESS_JUST_RESPAWN);
            ngx_start_cache_manager_processes(cycle, 1);

            /* allow new processes to start */
            // 阻塞等待100毫秒
            ngx_msleep(100);

            // 设置进程存活标志
            live = 1;

            // 关闭原来的worker进程
            // 新启动的进程不会发送shutdown信号
            // master进程调用，遍历ngx_processes数组，用kill发送信号
            // 走到worker进程的ngx_signal_handler()
            // 然后再是ngx_worker_process_cycle()的ngx_quit
            ngx_signal_worker_processes(cycle,
                                        ngx_signal_value(NGX_SHUTDOWN_SIGNAL));
        }

        if (ngx_restart) {
            ngx_restart = 0;

            // 启动worker进程，数量由配置决定，即worker_processes指令
            // 调用时传递的是#define NGX_PROCESS_RESPAWN       -3
            ngx_start_worker_processes(cycle, ccf->worker_processes,
                                       NGX_PROCESS_RESPAWN);
            ngx_start_cache_manager_processes(cycle, 0);

            // 设置进程存活标志
            live = 1;
        }

        // sigusr1， 重新打开日志文件，用来rotate日志
        if (ngx_reopen) {
            ngx_reopen = 0;
            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reopening logs");
            ngx_reopen_files(cycle, ccf->user);
            ngx_signal_worker_processes(cycle,
                                        ngx_signal_value(NGX_REOPEN_SIGNAL));
        }

        // 热更新nginx可执行文件
        if (ngx_change_binary) {
            ngx_change_binary = 0;
            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "changing binary");

            // 函数在core/nginx.c里
            ngx_new_binary = ngx_exec_new_binary(cycle, ngx_argv);
        }

        // 停止监听端口
        if (ngx_noaccept) {
            ngx_noaccept = 0;
            ngx_noaccepting = 1;
            ngx_signal_worker_processes(cycle,
                                        ngx_signal_value(NGX_SHUTDOWN_SIGNAL));
        }
    }   //master进程无限循环结束
}


// main()函数里调用，仅启动一个进程，没有fork
// master_process off;
void
ngx_single_process_cycle(ngx_cycle_t *cycle)
{
    ngx_uint_t  i;

    if (ngx_set_environment(cycle, NULL) == NULL) {
        /* fatal */
        exit(2);
    }

    // 调用所有模块的init_process，即进程启动时hook
    for (i = 0; cycle->modules[i]; i++) {
        if (cycle->modules[i]->init_process) {
            if (cycle->modules[i]->init_process(cycle) == NGX_ERROR) {
                /* fatal */
                exit(2);
            }
        }
    }

    // 无限循环，对外提供服务
    // ngx_signal_handler处理unix信号
    // 收到信号后设置ngx_quit/ngx_sigalrm/ngx_reconfigue等全局变量
    // 由无限循环检查这些变量再处理
    for ( ;; ) {
        ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "worker cycle");

        // 处理事件的核心函数, event模块里
        // 处理socket读写事件和定时器事件
        // 获取负载均衡锁，监听端口接受连接
        // 调用epoll模块的ngx_epoll_process_events
        // 然后处理超时事件和在延后队列里的所有事件
        // nginx大部分的工作量都在这里
        ngx_process_events_and_timers(cycle);

        // 检查是否处于退出状态
        // 这里不使用ngx_exiting变量，直接关闭端口退出
        if (ngx_terminate || ngx_quit) {

            // 所有模块的退出hook
            for (i = 0; cycle->modules[i]; i++) {
                if (cycle->modules[i]->exit_process) {
                    cycle->modules[i]->exit_process(cycle);
                }
            }

            // 删除pid，模块清理，关闭监听端口
            // 内部直接exit(0)退出
            ngx_master_process_exit(cycle);
        }

        // 重新配置，以当前cycle重新初始化，即reload
        if (ngx_reconfigure) {
            ngx_reconfigure = 0;    //标志量清零
            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reconfiguring");

            // 以当前cycle重新初始化
            cycle = ngx_init_cycle(cycle);
            if (cycle == NULL) {
                cycle = (ngx_cycle_t *) ngx_cycle;
                continue;
            }

            // ngx_cycle指针指向新的cycle
            ngx_cycle = cycle;
        }

        // 重新打开所有文件
        if (ngx_reopen) {
            ngx_reopen = 0;
            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reopening logs");
            ngx_reopen_files(cycle, (ngx_uid_t) -1);
        }
    } // 无限循环，对外提供服务
}


// 被ngx_master_process_cycle()调用
// 启动worker进程，数量由配置决定，即worker_processes指令
// 调用时传递的是#define NGX_PROCESS_RESPAWN       -3
static void
ngx_start_worker_processes(ngx_cycle_t *cycle, ngx_int_t n, ngx_int_t type)
{
    ngx_int_t      i;
    ngx_channel_t  ch;

    ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "start worker processes");

    ngx_memzero(&ch, sizeof(ngx_channel_t));

    // unix channel
    ch.command = NGX_CMD_OPEN_CHANNEL;

    for (i = 0; i < n; i++) {

        // os/unix/ngx_process.c产生进程，执行ngx_worker_process_cycle
        // 创建的进程都在ngx_processes数组里
        // 定义在os/unix/ngx_process.c
        // ngx_process_t    ngx_processes[NGX_MAX_PROCESSES];
        ngx_spawn_process(cycle, ngx_worker_process_cycle,
                          (void *) (intptr_t) i, "worker process", type);

        // 设置channel信息
        ch.pid = ngx_processes[ngx_process_slot].pid;
        ch.slot = ngx_process_slot;
        ch.fd = ngx_processes[ngx_process_slot].channel[0];

        // 建立channel，用于进程间通信
        ngx_pass_open_channel(cycle, &ch);
    }
}


static void
ngx_start_cache_manager_processes(ngx_cycle_t *cycle, ngx_uint_t respawn)
{
    ngx_uint_t       i, manager, loader;
    ngx_path_t     **path;
    ngx_channel_t    ch;

    manager = 0;
    loader = 0;

    path = ngx_cycle->paths.elts;
    for (i = 0; i < ngx_cycle->paths.nelts; i++) {

        if (path[i]->manager) {
            manager = 1;
        }

        if (path[i]->loader) {
            loader = 1;
        }
    }

    if (manager == 0) {
        return;
    }

    ngx_spawn_process(cycle, ngx_cache_manager_process_cycle,
                      &ngx_cache_manager_ctx, "cache manager process",
                      respawn ? NGX_PROCESS_JUST_RESPAWN : NGX_PROCESS_RESPAWN);

    ngx_memzero(&ch, sizeof(ngx_channel_t));

    ch.command = NGX_CMD_OPEN_CHANNEL;
    ch.pid = ngx_processes[ngx_process_slot].pid;
    ch.slot = ngx_process_slot;
    ch.fd = ngx_processes[ngx_process_slot].channel[0];

    ngx_pass_open_channel(cycle, &ch);

    if (loader == 0) {
        return;
    }

    ngx_spawn_process(cycle, ngx_cache_manager_process_cycle,
                      &ngx_cache_loader_ctx, "cache loader process",
                      respawn ? NGX_PROCESS_JUST_SPAWN : NGX_PROCESS_NORESPAWN);

    ch.command = NGX_CMD_OPEN_CHANNEL;
    ch.pid = ngx_processes[ngx_process_slot].pid;
    ch.slot = ngx_process_slot;
    ch.fd = ngx_processes[ngx_process_slot].channel[0];

    ngx_pass_open_channel(cycle, &ch);
}


static void
ngx_pass_open_channel(ngx_cycle_t *cycle, ngx_channel_t *ch)
{
    ngx_int_t  i;

    for (i = 0; i < ngx_last_process; i++) {

        if (i == ngx_process_slot
            || ngx_processes[i].pid == -1
            || ngx_processes[i].channel[0] == -1)
        {
            continue;
        }

        ngx_log_debug6(NGX_LOG_DEBUG_CORE, cycle->log, 0,
                      "pass channel s:%i pid:%P fd:%d to s:%i pid:%P fd:%d",
                      ch->slot, ch->pid, ch->fd,
                      i, ngx_processes[i].pid,
                      ngx_processes[i].channel[0]);

        /* TODO: NGX_AGAIN */

        ngx_write_channel(ngx_processes[i].channel[0],
                          ch, sizeof(ngx_channel_t), cycle->log);
    }
}


// master进程调用，遍历ngx_processes数组，用kill发送信号
static void
ngx_signal_worker_processes(ngx_cycle_t *cycle, int signo)
{
    ngx_int_t      i;
    ngx_err_t      err;
    ngx_channel_t  ch;

    ngx_memzero(&ch, sizeof(ngx_channel_t));

#if (NGX_BROKEN_SCM_RIGHTS)

    ch.command = 0;

#else

    switch (signo) {

    case ngx_signal_value(NGX_SHUTDOWN_SIGNAL):
        ch.command = NGX_CMD_QUIT;
        break;

    case ngx_signal_value(NGX_TERMINATE_SIGNAL):
        ch.command = NGX_CMD_TERMINATE;
        break;

    case ngx_signal_value(NGX_REOPEN_SIGNAL):
        ch.command = NGX_CMD_REOPEN;
        break;

    default:
        ch.command = 0;
    }

#endif

    ch.fd = -1;


    // 遍历ngx_processes数组，用kill发送信号
    for (i = 0; i < ngx_last_process; i++) {

        ngx_log_debug7(NGX_LOG_DEBUG_EVENT, cycle->log, 0,
                       "child: %i %P e:%d t:%d d:%d r:%d j:%d",
                       i,
                       ngx_processes[i].pid,
                       ngx_processes[i].exiting,
                       ngx_processes[i].exited,
                       ngx_processes[i].detached,
                       ngx_processes[i].respawn,
                       ngx_processes[i].just_spawn);

        if (ngx_processes[i].detached || ngx_processes[i].pid == -1) {
            continue;
        }

        // 新启动的进程不会发送信号
        if (ngx_processes[i].just_spawn) {
            ngx_processes[i].just_spawn = 0;
            continue;
        }

        if (ngx_processes[i].exiting
            && signo == ngx_signal_value(NGX_SHUTDOWN_SIGNAL))
        {
            continue;
        }

        // 通常是使用channel发送信号
        if (ch.command) {
            if (ngx_write_channel(ngx_processes[i].channel[0],
                                  &ch, sizeof(ngx_channel_t), cycle->log)
                == NGX_OK)
            {
                if (signo != ngx_signal_value(NGX_REOPEN_SIGNAL)) {
                    ngx_processes[i].exiting = 1;
                }

                continue;
            }
        }

        ngx_log_debug2(NGX_LOG_DEBUG_CORE, cycle->log, 0,
                       "kill (%P, %d)", ngx_processes[i].pid, signo);

        // kill发送信号
        if (kill(ngx_processes[i].pid, signo) == -1) {
            err = ngx_errno;
            ngx_log_error(NGX_LOG_ALERT, cycle->log, err,
                          "kill(%P, %d) failed", ngx_processes[i].pid, signo);

            if (err == NGX_ESRCH) {
{'fraction_non_alphanumeric': 0.10149604723306314, 'fraction_numerical': 0.007104973481437006, 'mean_word_length': 1.9383269626580417, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 115, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 28, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1350976', 'n_tokens_mistral': 16352, 'n_tokens_neox': 16357, 'n_words': 2043}