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

相关文章
相关标签/搜索