nginx 源碼學習筆記(十五)—— ngx_master_process_cycle 多進程(一)

來源:互聯網
上載者:User

瞭解core模組之前還應改學習ngx_start_worker_processes函數,今天我就來詳細學一下這個方法,主要內容來自於http://blog.sina.com.cn/s/blog_677be95b0100iivk.html。

 

nginx的進程啟動過程是在ngx_master_process_cycle(src/os/unix/ngx_process_cycle.c)中完成的(單進程是通過ngx_single_process_cycle完成,這裡只分析多進程的情況),在ngx_master_process_cycle中,會根據設定檔的worker_processes值建立多個子進程,即一個master進程和多個worker進程。進程之間、進程與外部之間保持通訊,進程之間是通過socketpair進行通訊的,socketpair是一對全雙工系統的無名socket,可以當作管道使用,和管道不同的是,每條socket既可以讀也可以寫,而管道只能用於寫或者用於讀;進程與外部之間是通過訊號通訊的。

master進程主要進行一些全域性的初始化工作和管理worker的工作;事件處理是在worker中進行的。

進程啟動的過程中,有一些重要的全域資料會被設定,最重要的是進程表ngx_processes,master每建立一個worker都會把一個設定好的ngx_process_t結構變數放入ngx_processes中,進程表長度為1024,剛建立的進程存放在ngx_process_slot位置,ngx_last_process是進程表中最後一個存量進程的下一個位置,ngx_process_t是進程在nginx中的抽象:

src/os/unix/ngx_process.htypedef void (*ngx_spawn_proc_pt) (ngx_cycle_t *cycle, void *data);typedef struct {    ngx_pid_t           pid;                 //進程id    int                 status;              //進程狀態    ngx_socket_t        channel[2];          //socketpair建立的socket控制代碼    ngx_spawn_proc_pt   proc;                //進程執行函數    void               *data;                //執行函數的參數    char               *name;                //名稱    unsigned            respawn:1;           //重新建立    unsigned            just_spawn:1;        //第一次建立的    unsigned            detached:1;          //分離的    unsigned            exiting:1;           //正在退出的    unsigned            exited:1;            //退出過的} ngx_process_t;

 

處理序間通訊是利用socketpair建立的一對socket進行的,通訊中傳輸的是ngx_channel_t結構變數:

ypedef struct {     ngx_uint_t  command;     ngx_pid_t   pid;                        //發送方進程id     ngx_int_t   slot;                       //發送方進程表中位移     ngx_fd_t    fd;                         //發送給對方的控制代碼} ngx_channel_t;(src/os/unix/ngx_channel.h)/*command是要發送的命令,有5種:#define NGX_CMD_OPEN_CHANNEL   1#define NGX_CMD_CLOSE_CHANNEL  2#define NGX_CMD_QUIT           3#define NGX_CMD_TERMINATE      4#define NGX_CMD_REOPEN         5*/

 

進程的啟動過程是比較重要的一個環節,為了把這個過程分析透徹,下面會多採用首先分析ngx_master_process_cycle函數,可以分解為以下各步驟:

1、master設定一些需要處理的訊號,這些訊號包括

SIGCHLD,SIGALRM,SIGIO,SIGINT,NGX_RECONFIGURE_SIGNAL(SIGHUP),NGX_REOPEN_SIGNAL(SIGUSR1),
NGX_NOACCEPT_SIGNAL(SIGWINCH),NGX_TERMINATE_SIGNAL(SIGTERM),NGX_SHUTDOWN_SIGNAL(SIGQUIT),
NGX_CHANGEBIN_SIGNAL(SIGUSR2);

 

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));

2、調用ngx_setproctilte設定進程標題,title = "master process" + ngx_argv[0] + ... + ngx_argv[ngx_argc-1];

 

title = ngx_pnalloc(cycle->pool, size);    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);

3、調用ngx_start_worker_processes(cycle, ccf->worker_processes, NGX_PROCESS_RESPAWN)啟動worker進程;

 

ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);    ngx_start_worker_processes(cycle, ccf->worker_processes,                               NGX_PROCESS_RESPAWN);

4、調用ngx_start_cache_manager_processes(cycle, 0)開機檔案cache管理進程,有些模組需要檔案cache,比如fastcgi模組,這些模組會把檔案cache路徑添加到cycle->paths中,檔案cache管理進程會定期調用這些模組的檔案cache處理鉤子處理一下檔案cache;

 

ngx_start_cache_manager_processes(cycle, 0);

注釋代碼的方式分析。5、master迴圈處理訊號量。

src/os/unix/ngx_process_cycle.cdelay = 0;sigio = 0;live = 1;for ( ;; ) {    //delay用來設定等待worker推出的時間,master接受了退出訊號後,    //首先發送退出訊號給worker,而worker退出需要一些時間    if (delay) {        if (ngx_sigalrm) {            sigio = 0;            delay *= 2;            ngx_sigalrm = 0;        }        ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0,                       "termination cycle: %d", 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(&set);    ngx_time_update();    ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0,                   "wake up, sigio %i", sigio);    //收到了SIGCHLD訊號,有worker退出(ngx_reap == 1)    if (ngx_reap) {        ngx_reap = 0;        ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "reap children");        //處理所有worker,如果有worker異常退出,則重啟        //這個worker,如果所有的worker都退出了,則返回0        live = ngx_reap_children(cycle);    }    //如果worker都退出了    //並且收到了NGX_CMD_TERMINATE命令或者SIGTERM訊號或SIGINT訊號(ngx_terminate ==1)    //或NGX_CMD_QUIT命令或SIGQUIT訊號(ngx_quit == 1),則master退出    if (!live && (ngx_terminate || ngx_quit)) {        ngx_master_process_exit(cycle);    }    //收到了NGX_CMD_TERMINATE命令或者SIGTERM訊號或SIGINT訊號(ngx_terminate ==1)    //通知所有worker退出,並且等待worker退出    if (ngx_terminate) {        if (delay == 0) {            //設定延時            delay = 50;        }        if (sigio) {            sigio--;            continue;        }        sigio = ccf->worker_processes + 2 /* cache processes */;        if (delay > 1000) {            //延時已到,給所有worker發送SIGKILL訊號,強制殺死worker            ngx_signal_worker_processes(cycle, SIGKILL);        } else {            //給所有worker發送SIGTERM訊號,通知worker退出            ngx_signal_worker_processes(cycle,                                   ngx_signal_value(NGX_TERMINATE_SIGNAL));        }        continue;    }    //NGX_CMD_QUIT命令或SIGQUIT訊號(ngx_quit == 1)    if (ngx_quit) {        //給所有的worker發送SIGQUIT訊號        ngx_signal_worker_processes(cycle,                                    ngx_signal_value(NGX_SHUTDOWN_SIGNAL));        //關閉所有監聽socket        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;    }    //收到SIGHUP訊號    if (ngx_reconfigure) {        ngx_reconfigure = 0;        //代碼已被替換,重啟worker,不需要重新初始化配置。        if (ngx_new_binary) {            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");        //重新初始化配置        cycle = ngx_init_cycle(cycle);        if (cycle == NULL) {            cycle = (ngx_cycle_t *) ngx_cycle;            continue;        }        //重啟worker        ngx_cycle = cycle;        ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx,                                               ngx_core_module);        ngx_start_worker_processes(cycle, ccf->worker_processes,                                   NGX_PROCESS_JUST_RESPAWN);        ngx_start_cache_manager_processes(cycle, 1);        live = 1;        ngx_signal_worker_processes(cycle,                                    ngx_signal_value(NGX_SHUTDOWN_SIGNAL));    }    //當ngx_noaccepting==1時,會把ngx_restart設為1,重啟worker    if (ngx_restart) {        ngx_restart = 0;        ngx_start_worker_processes(cycle, ccf->worker_processes,                                   NGX_PROCESS_RESPAWN);        ngx_start_cache_manager_processes(cycle, 0);        live = 1;    }    //收到SIGUSR1訊號,重新開啟log檔案    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));    }    //收到SIGUSER2,熱代碼替換    if (ngx_change_binary) {        ngx_change_binary = 0;        ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "changing binary");        ngx_new_binary = ngx_exec_new_binary(cycle, ngx_argv);    }    //收到SIGWINCH訊號不在接受請求,worker退出,master不退出    if (ngx_noaccept) {        ngx_noaccept = 0;        ngx_noaccepting = 1;        ngx_signal_worker_processes(cycle,                                    ngx_signal_value(NGX_SHUTDOWN_SIGNAL));    }}

 

下面總結下,也希望各位同學,再看總結之前,已經閱讀了(起碼是看了一遍)上面的代碼注釋!!!

該總結來自於http://blog.csdn.net/lu_ming/article/details/5144427 非常感激作者無私奉獻。

ngx_master_process_cycle()函數,這個函數會啟動背景工作處理序幹活,並且會處理訊號量,處理的過程中會殺死或者建立新的進程。

a)  阻塞所有nginx關心的訊號;

b)  設定進程的title(如果你用ps –aux來查看就可以分清master與worker進程,這就是title的作用。);

c)  按照ngx_core_conf_t中worker_processes數,啟動若干個work進程;

d)  啟動一個緩衝管理進程;

e)  初始化幾個標誌:ngx_new_binary = 0; delay = 0; live = 1;

f)  後面一個迴圈對不同的狀態進行不同處理,而那些狀態多數是進程收到的不同訊號。下面是各個處理的詳解:

a)   delay不為0,如果收到SIGALRM訊號ngx_sigalrm設為1,將delay時間乘以2;最後設定一個即時類型的計時器;

b)   掛起當前進程,等到有訊號,就會從掛起狀態退出,繼續執行;

c)   退出掛起狀態後,根據作業系統時間重新更新目前時間;

d)   ngx_reap為1(收到SIGCHLD訊號有worker退出(ngx_reap==1)),調用ngx_reap_children()回收子進程;

e)   如果子進程都退出了(!live)且當前進程收到ngx_signal_value(NGX_SHUTDOWN_SIGNAL)或ngx_signal_value(NGX_TERMINATE_SIGNAL)訊號,本進程進行退出處理(ngx_master_process_exit());退出處理先刪除pid檔案,然後將調用所有模組的進程退出鉤子,銷毀記憶體池對象;

f)   如果ngx_terminate為1,delay為0,就設成50;如果delay>1000,向work進程發送SIGKILL訊號,否則向work進程發送ngx_signal_value(NGX_TERMINATE_SIGNAL)訊號;

g)   如果ngx_quit為1,向work進程發送ngx_signal_value(NGX_SHUTDOWN_SIGNAL)訊號,然後將所有全域listening中的socket全關閉;continue;

h)   如果ngx_reconfigure為1(ngx_signal_value(NGX_RECONFIGURE_SIGNAL)訊號對應),就重新讀取config檔案;重新建立並初始化ngx_cycle對象,啟動work進程,啟動緩衝管理進程,將live設為1,調用ngx_signal_worker_processes()發送ngx_signal_value(NGX_SHUTDOWN_SIGNAL)訊號;

i)   ngx_new_binary為1(表示是新啟動的一個進程),啟動work進程,啟動緩衝管理進程,然後將ngx_noaccepting設為0;continue;

j)   如果ngx_restart為1(當ngx_noaccepting=1的時候會把ngx_restart設為1,重啟worker),啟動work進程,啟動緩衝管理進程,live設為1;

k)   如果ngx_reopen為1(ngx_signal_value(NGX_REOPEN_SIGNAL)訊號對應),則重新找開log檔案,調用ngx_signal_worker_processes()發送ngx_signal_value(NGX_REOPEN_SIGNAL)訊號;

l)   如果ngx_change_binary為1(ngx_signal_value(NGX_CHANGEBIN_SIGNAL)訊號對應),調用ngx_exec_new_binary()執行新進程;

m)   如果ngx_noaccept為1(ngx_signal_value(NGX_NOACCEPT_SIGNAL)對應),設ngx_noaccepting為1,調用ngx_signal_worker_processes()發送ngx_signal_value(NGX_SHUTDOWN_SIGNAL)訊號。

 

下一節,繼續講子進程建立,和所做的操作。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.