在nginx的worker进程启动后,便阻塞在epoll_wait函数(ngx_epoll_process_events),等待http请求的到来,那么当一个http请求到来之时,nginx是如何作出相应的呢?下面介绍该过程。
首先,在ngx_event_process_init函数中,可看到rev->handler被初始化为函数ngx_event_accept,因此,在函数
ngx_epoll_process_events中,对rev->handler的调用会调到ngx_event_accept函数。该函数会调用ls->handler(c),这个handler又是在哪里初始化的呢?该函数是在ngx_http_add_listening中进行初始化的,具体语句为:ls->handler= ngx_http_init_connection,因此最终会在ngx_http_init_connection中,一步一步调用至ngx_http_core_run_phases,该函数中,会遍历所有的11个阶段,若该阶段有挂载函数,则会调用该函数。
具体而言,以ngx_http_static_module为例,该模块挂载在
NGX_HTTP_CONTENT_PHASE中,因此当NGX_HTTP_CONTENT_PHASE到来时,会调用ngx_http_static_handler函数,该函数中会调用ngx_http_send_header,以及
ngx_http_output_filter函数,这两个函数最终会调用ngx_http_write_filter函数,在该函数中会调用ngx_linux_sendfile_chain函数发送数据。