nginx 0 8 38原始碼探秘(五)

2021-09-30 07:28:23 字數 1528 閱讀 6308

前面把初始化流程分析完成,可以發現,nginx是先把各模組的指令初始化完成後,再初始化子程序,最後等待客戶請求到來。下面開始分析nginx的處理流程。

ngx_event_accept是整個處理流程的開始,它呼叫accept等待連線的到來,當有新連線到來時,通過ngx_get_connection取得乙個空閒連線,註冊連線的傳送接收鉤子(還記得第一章的ngx_linux_io ?):

然後將該連線新增到epoll事件中,觸發ngx_listening_t的handler:ngx_http_init_connection,分析一下這個函式:

當連線的資料到來時,就接著呼叫ngx_http_init_request。

ngx_http_init_request函式初始化ngx_http_request_t結構,註冊了幾個handler:rev->handler = ngx_http_process_request_line,r->read_event_handler = ngx_http_block_reading,r->log_handler = ngx_http_log_error_handler,設定了http狀態r->http_state = ngx_http_reading_request_state,這是一系列列舉值:

最後呼叫ngx_http_process_request_line。

ngx_http_process_request_line函式首先呼叫ngx_http_read_request_header接收資料,資料儲存在r->header_in緩衝區中。接著利用ngx_http_parse_request_line解析http request-line(如:get / http/1.1),如果解析沒有發生錯誤,重新註冊rev->handler = ngx_http_process_request_headers,呼叫ngx_http_process_request_headers。

ngx_http_process_request_headers函式使用ngx_http_parse_header_line解析head field,然後查詢hash得到hh(型別為ngx_http_header_t),接著呼叫hh註冊的handler,這些handler在ngx_http_headers_in變數裡註冊。

得到head field的(key,value)值對後,改變狀態r->http_state = ngx_http_process_request_state,呼叫ngx_http_process_request_header分析head field的合法性,最後呼叫ngx_http_process_request。

ngx_http_process_request函式又註冊了幾個handler:c->read->handler = ngx_http_request_handler,c->write->handler = ngx_http_request_handler,r->read_event_handler = ngx_http_block_reading。緊接著呼叫ngx_http_handler,這個函式做了一件非常重要的事情,執行各http phase註冊的handler。

這涉及一大串的handler,下一章再慢慢吃了。

nginx 0 8 38 安裝配置備忘

nginx 0.8.38 安裝配置備忘 據說 nginx 是這幾年來 web 伺服器的後起之秀,是 apache殺手 由俄羅斯程式設計師編寫。是乙個輕量級的 web 伺服器,也是據說,占用資源少,高併發,在某些情況下,效率是 apache 的 10 倍。國內外很多大型門戶站都在用。經不住蠱惑,決定在...

nginx原始碼學習(五)

我們接著上篇文章來講講ngx get options函式。這個函式就在nginx.c檔案中,我們來看看。引數argc,argv我們在前面的文章中都已經提到了,在這裡我們看ngx get options裡面的for迴圈。它的作用就是把所有的執行時引數迴圈一遍,判斷是不是合法。例如 nginx s st...

nginx原始碼分析 從原始碼看nginx框架總結

nginx原始碼總結 1 中沒有特別繞特別彆扭的編碼實現,從變數的定義呼叫函式的實現封裝,都非常恰當,比如從函式命名或者變數命名就可以看出來定義的大體意義,函式的基本功能,再好的架構實現在編碼習慣差的人實現也會黯然失色,如果透徹理解 的實現,領悟架構的設計初衷,覺得每塊 就想經過耐心雕琢一樣,不僅僅...