nginx—sendfile

Nginx高級篇sendfile配置

  • sendfile: 設置爲on表示啓動高效傳輸文件的模式。sendfile可讓Nginx在傳輸文件時直接在磁盤和tcp socket之間傳輸數據。若是這個參數不開啓,會先在用戶空間(Nginx進程空間)申請一個buffer,用read函數把數據從磁盤讀到cache,再從cache讀取到用戶空間的buffer,再用write函數把數據從用戶空間的buffer寫入到內核的buffer,最後到tcp socket。開啓這個參數後可讓數據不用通過用戶buffer。
  • Linux kernel 2.2以前,(如圖)讀寫數據基本都是使用read系統調用和write系調用,以nginx來講若是一個請求創建,從磁盤的文件到網絡鏈接之間會經過硬件(DMA)---內核層---用戶層屢次讀寫系統來完成文件數據的複製傳輸:從內核層用read系統調用讀到用戶層,再從用戶層用write系統調用寫到內核層,每一次用戶層到內核層的進行一次上下文轉換,這種代價是很是昂貴的。甚至在沒有數據變化時這種複製尤爲顯得多餘。若是nginx接受大量併發請求,這種系統調用就會很是頻繁,服務器的性能就會降低。
  • nginx—sendfile

  • 在Linux kernel2.2版本以後出現了一種叫作「零拷貝(zero-copy)」系統調用機制,目前不少應用服務器如apache、samba、nginx都支持sendfile。注意:sendfile系統調用是一種文件傳輸的系統調用和kernel系統調用關係不大。
  • nginx—sendfile
  • 如圖所示,nginx在支持了sendfile系統調用後,避免了內核層與用戶層的上線文切換(content swith)工做,大大減小了系統性能的開銷。可使用man 8 sendfile 進一步瞭解sendfile系統調用。
  • nginx—sendfile
  • 如下是對參數解釋

out_fd
a file descriptor, open for writing, for the data to be written
in_fd
a file descriptor, open for reading, for the data to be read
offset
the offset in the input file to start transfer (e.g. a value of 0 indicates the beginning of the file). This is passed into the function and updated when the function returns.
count
the number of bytes to be transferredhtml

正常狀況下函數會返回被寫入的字節數,若是出錯就返回-1linux

咱們都知道在linux系統裏文件描述符fd,能夠是一個真實的文件或者是一個設備,例如一個網絡socket,(固然linux世界裏一切皆文件,這裏只是具體區別一下。)senfile須要輸入的文件描述符是一個支持mmap的真實文件或者設備,那麼socket就不能做爲輸入的fd,而輸出的fd是能夠的。nginx

相關文章
相關標籤/搜索