图解Linux的IO模型和相关技术( 二 )

  • epoll_create :
内核会产生一个epoll 实例数据结构并返回一个文件描述符epfd 。
  • epoll_ctl :
对文件描述符 fd 和 其监听事件 epoll_event 进行注册,删除,或者修改其监听事件 epoll_event。
SYNOPSIS#include <sys/epoll.h>int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);DESCRIPTIONThis system call is used to add, modify, or remove entries in the interest list of the epoll(7) instance referred to by the file descriptor epfd. It requests that the operation op be performedfor the target file descriptor, fd.Valid values for the op argument are:EPOLL_CTL_ADDAdd an entry to the interest list of the epoll file descriptor, epfd. The entry includes the file descriptor, fd, a reference to the corresponding open file description (see epoll(7)and open(2)), and the settings specified in event.EPOLL_CTL_MODChange the settings associated with fd in the interest list to the new settings specified in event.EPOLL_CTL_DELRemove (deregister) the target file descriptor fd from the interest list. The event argument is ignored and can be NULL (but see BUGS below).
  • epoll_wait :
阻塞等待注册的事件发生,返回事件的数目,并将触发的可用事件写入epoll_events数组中 。
扩展
  • https://www.zhihu.com/question/39792257
  • https://programmer.group/5dc6d7d3c6146.html
其他IO优化技术man 2 mmapman 2 sendfileman 2 forkmmap:就是在用户的虚拟地址空间中寻找空闲的一段地址进行对文件的操作,不必再调用read、write系统调用,它的最终目的是将磁盘中的文件映射到用户进程的虚拟地址空间,实现用户进程对文件的直接读写,减少了文件复制的开销,提高了用户的访问效率 。
以读为例:
图解Linux的IO模型和相关技术

文章插图
 
  • 深入剖析mmap原理 - 从三个关键问题说起: https://www.jianshu.com/p/eece39beee20
  • 使用场景
kafka的数据文件就是用的mmap,写入文件,可以不经过用户空间到内核的拷贝,直接内核空间落盘 。
再比如JAVA中的MAppedByteBuffer底层在Linux就是mmap 。
sendfile:
图解Linux的IO模型和相关技术

文章插图
 
sendfile系统调用在两个文件描述符之间直接传递数据(完全在内核中操作),从而避免了数据在内核缓冲区和用户缓冲区之间的拷贝,操作效率很高,被称之为零拷贝 。
  • 使用场景
比如 kafka,消费者进行消费时,kafka直接调用 sendfile(Java中的FileChannel.transferTo),实现内核数据从内存或数据文件中读出,直接发送到网卡,而不需要经过用户空间的两次拷贝,实现了所谓"零拷贝" 。
再比如Tomcat、Nginx、Apache等web服务器返回静态资源等,将数据用网络发送出去,都运用了sendfile 。
forkman 2 fork创建子进程有三种方式:
  • fork,调用后,子进程有自己的pid和task_struct结构,基于父进程的所有数据资源进行副本拷贝,主要是复制自己的指针,并不会复制父进程的虚存空间,并且父子进程同时进行,变量互相隔离,互不干扰 。
现在Linux中是采取了Copy-On-Write(COW,写时复制)技术,为了降低开销,fork最初并不会真的产生两个不同的拷贝,因为在那个时候,大量的数据其实完全是一样的 。写时复制是在推迟真正的数据拷贝 。若后来确实发生了写入,那意味着父进程和子进程的数据不一致了,于是产生复制动作,每个进程拿到属于自己的那一份,这样就可以降低系统调用的开销 。
NOTESUnderLinux,fork()is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory required to duplicate the parent's page tables, and to create a uniquetask structure for the child.
  • vfork,vfork系统调用不同于fork,用vfork创建的子进程与父进程共享地址空间,也就是说子进程完全运行在父进程的地址空间上,也就是子进程对虚拟地址空间任何数据的修改同样为父进程所见 。并且vfork完子进程,父进程是阻塞等待子进程结束才会继续 。
  • clone,可以认为是fork 与 vfork的混合用法 。由用户通过参clone_flags 的设置来决定哪些资源共享,哪些资源副本拷贝 。由标志CLONE_VFORK来决定子进程在执行时父进程是阻塞还是运行,若没有设置该标志,则父子进程同时运行,设置了该标志,则父进程挂起,直到子进程结束为止 。