您的位置:首页 > 运维架构 > Nginx

nginx代码分析【1】

2013-03-10 17:47 387 查看
1. 代码分析准备

a)build脚本

#!/bin/bash                                                                                                                  

/usr/local/nginx/sbin/nginx -s stop
rm -fr /usr/local/nginx/
#./configure --with-debug --add-module=/Users/xuqiang/nginx/nginx/src/modules/
./configure
make -j 8
make install
b) 修改配置文件auto/cc/conf

# add debug mode
ngx_compile_opt="-c -g"


2. 代码分析

main

ngx_debug_init
ngx_strerror_init
ngx_time_init
ngx_regex_init 
ngx_log_init
ngx_log_init
// 因为Nginx支持热切换可执行文件,为了保证在切换前后不丢失所监听的套接字,在切换之前Nginx会把当前的listen fds 写入环境变     量,在切换以后通过读取环境变量获得这些listen fds
ngx_add_inherited_sockets 
// 删除old cycle,生成new cycle,调用ngx_command_t的set函数设定配置文件,调用module的init_module初始化
ngx_init_cycle
ngx_daemon
ngx_create_pidfile
ngx_master_process_cycle
  ngx_start_worker_processes
    创建worker process,进程处理函数为ngx_worker_process_cycle
    ngx_worker_process_cycle内部调用ngx_worker_process_init初始化work process,该函数中处理如下:
     foreach modules { call init_module }
    ngx_start_cache_manager_processes


3. http core module(ngx_http.c)

ngx_http.c中定义了处理http请求的module。command定义如下:

static ngx_command_t  ngx_http_commands[] = {

    { ngx_string("http"),
      NGX_MAIN_CONF|NGX_CONF_BLOCK|NGX_CONF_NOARGS,
      ngx_http_block,
      0,
      0,
      NULL },

      ngx_null_command
};
对应nginx.conf中的如下配置:

http {
    include       mime.types;
    default_type  application/octet-stream;
    //....
}
解析该配置的函数为ngx_http_block,主要逻辑如下:

foreach http modules
{
create_main_conf
preconfiguration
init_main_conf
merge_srv_conf
merge_loc_conf
}
create location trees
ngx_http_init_phases注册各个phrase的handler
我们如果是http module的话,将会被该module初始化。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: