阻塞IO模型(Blocking I/O)

Linux 內核一開始提供了 read 與 write 阻塞式操作,
- 當客戶端連接時,會在對應行程的檔案描述符目錄(/proc/行程號/fd)生成對應的檔案描述符(0 標準輸入;1 標準輸出;2 標準錯誤輸出;),比如 fd 8 , fd 9;
- 應用程式需要讀取的時候,通過系統呼叫
read (fd8)讀取,如果資料還沒到來,此應用程式的行程或執行緒會阻塞等待,
man 2 read
概述
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
描述
read() 從檔案描述符 fd 中讀取 count 位元組的資料并放入從 buf 開始的緩沖區中.
如果 count 為零,read()回傳0,不執行其他任何操作. 如果 count 大于SSIZE_MAX,那么結果將不可預料.
回傳值
成功時回傳讀取到的位元組數(為零表示讀到檔案描述符), 此回傳值受檔案剩余位元組數限制.當回傳值小于指定的位元組數時 并不意味著錯誤;這可能是因為當前可讀取的位元組數小于指定的 位元組數(比如已經接近檔案結尾,或
者正在從管道或者終端讀取數 據,或者 read()被信號中斷). 發生錯誤時回傳-1,并置 errno 為相應值.在這種情況下無法得知檔案偏移位置是否有變化.
問題
如果出現了很多的客戶端連接,比如1000個,那么應用程式就會啟用1000個行程或執行緒阻塞等待,此時會出現性能問題:
- CPU 會不停的切換,造成行程或執行緒背景關系切換開銷,實際讀取IO的時間占比會下降,造成CPU算力浪費,
因此,推動了 non-blocking I/O 的誕生,
非阻塞IO模型(non-blocking I/O)

此時,Linux 內核一開始提供了 read 與 write 非阻塞式操作,可以通過socket設定SOCK_NONBLOCK標記 ,
- 此時應用程式就不需要每一個檔案描述符一個執行緒去處理,可以只有一個執行緒不停輪詢去讀取
read,如果沒有資料到來,也會直接回傳, - 如果有資料,則可以調度去處理業務邏輯,
man 2 socket
Since Linux 2.6.27, the type argument serves a second purpose: in addition to specifying a socket type, it may include the bitwise OR of any of the following values, to modify the behavior of
socket():
SOCK_NONBLOCK Set the O_NONBLOCK file status flag on the open file description (see open(2)) referred to by the new file descriptor. Using this flag saves extra calls to fcntl(2) to achieve
the same result.
從這里可以看出來 socket Linux 2.6.27內核開始支持非阻塞模式,
問題
同理,當出現了很多的客戶端連接,比如1000個,那就會觸發1000次系統呼叫,(1000次系統呼叫開銷也很客觀)
因此,有了 select,
IO復用模型(I/O multiplexing) - select

此時,Linux 內核一開始提供了 select 操作,可以把1000次的系統呼叫,簡化為一次系統呼叫,輪詢發生在內核空間,
select系統呼叫會回傳可用的 fd集合,應用程式此時只需要遍歷可用的 fd 集合, 去讀取資料進行業務處理即可,
man 2 select
SYNOPSIS
#include <sys/select.h>
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
DESCRIPTION
select() allows a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file
descriptor is considered ready if it is possible to perform a corresponding I/O operation (e.g., read(2), or a sufficiently small write(2)) without blocking.
select() can monitor only file descriptors numbers that are less than FD_SETSIZE; poll(2) and epoll(7) do not have this limitation. See BUGS.
可以看到支持傳輸多個檔案描述符交由內核輪詢,
問題
雖然從1000次系統呼叫,降為一次系統呼叫的開銷,但是系統呼叫開銷中需要傳參1000個檔案描述符,這也會造成一定的記憶體開銷,
因此,有了 epoll,
select() can monitor only file descriptors numbers that are less than FD_SETSIZE; poll(2) and epoll(7) do not have this limitation. See BUGS.
IO復用模型(I/O multiplexing) - epoll

man epoll
man 2 epoll_create
man 2 epoll_ctl
man 2 epoll_wait
- epoll:
SYNOPSIS
#include <sys/epoll.h>
DESCRIPTION
The epoll API performs a similar task to poll(2): monitoring multiple file descriptors to see if I/O is possible on any of them. The epoll API can be used either as an edge-triggered or a
level-triggered interface and scales well to large numbers of watched file descriptors.
The central concept of the epoll API is the epoll instance, an in-kernel data structure which, from a user-space perspective, can be considered as a container for two lists:
? The interest list (sometimes also called the epoll set): the set of file descriptors that the process has registered an interest in monitoring.
? The ready list: the set of file descriptors that are "ready" for I/O. The ready list is a subset of (or, more precisely, a set of references to) the file descriptors in the interest list.
The ready list is dynamically populated by the kernel as a result of I/O activity on those file descriptors.
- 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);
DESCRIPTION
This 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 performed
for the target file descriptor, fd.
Valid values for the op argument are:
EPOLL_CTL_ADD
Add 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_MOD
Change the settings associated with fd in the interest list to the new settings specified in event.
EPOLL_CTL_DEL
Remove (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 mmap
man 2 sendfile
man 2 fork
mmap:
就是在用戶的虛擬地址空間中尋找空閑的一段地址進行對檔案的操作,不必再呼叫read、write系統呼叫,它的最終目的是將磁盤中的檔案映射到用戶行程的虛擬地址空間,實作用戶行程對檔案的直接讀寫,減少了檔案復制的開銷,提高了用戶的訪問效率,
以讀為例:

-
深入剖析mmap原理 - 從三個關鍵問題說起: https://www.jianshu.com/p/eece39beee20
-
使用場景
kafka的資料檔案就是用的mmap,寫入檔案,可以不經過用戶空間到內核的拷貝,直接內核空間落盤,
再比如Java中的MappedByteBuffer底層在Linux就是mmap,
sendfile:

sendfile系統呼叫在兩個檔案描述符之間直接傳遞資料(完全在內核中操作),從而避免了資料在內核緩沖區和用戶緩沖區之間的拷貝,操作效率很高,被稱之為零拷貝,
- 使用場景
比如 kafka,消費者進行消費時,kafka直接呼叫 sendfile(Java中的FileChannel.transferTo),實作內核資料從記憶體或資料檔案中讀出,直接發送到網卡,而不需要經過用戶空間的兩次拷貝,實作了所謂"零拷貝",
再比如Tomcat、Nginx、Apache等web服務器回傳靜態資源等,將資料用網路發送出去,都運用了sendfile,
fork
man 2 fork
創建子行程有三種方式:
fork,呼叫后,子行程有自己的pid和task_struct結構,基于父行程的所有資料資源進行副本拷貝,主要是復制自己的指標,并不會復制父行程的虛存空間,并且父子行程同時進行,變數互相隔離,互不干擾,
現在Linux中是采取了Copy-On-Write(COW,寫時復制)技術,為了降低開銷,fork最初并不會真的產生兩個不同的拷貝,因為在那個時候,大量的資料其實完全是一樣的,
寫時復制是在推遲真正的資料拷貝,若后來確實發生了寫入,那意味著父行程和子行程的資料不一致了,于是產生復制動作,每個行程拿到屬于自己的那一份,這樣就可以降低系統呼叫的開銷,
NOTES
Under Linux, 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 unique
task structure for the child.
-
vfork,vfork系統呼叫不同于fork,用vfork創建的子行程與父行程共享地址空間,也就是說子行程完全運行在父行程的地址空間上,也就是子行程對虛擬地址空間任何資料的修改同樣為父行程所見,并且vfork完子行程,父行程是阻塞等待子行程結束才會繼續, -
clone,可以認為是fork與vfork的混合用法,由用戶通過參clone_flags 的設定來決定哪些資源共享,哪些資源副本拷貝, 由標志CLONE_VFORK來決定子行程在執行時父行程是阻塞還是運行,若沒有設定該標志,則父子行程同時運行,設定了該標志,則父行程掛起,直到子行程結束為止, -
總結
fork的用途
一個行程希望對自身進行副本拷貝,從而父子行程能同時執行不同段的代碼,
比如redis的RDB持久化就是采用的就是fork,保證副本拷貝的時點準確,并且速度快,不影響父行程繼續提供服務,vfork的用途
用vfork創建的行程主要目的是用exec函式先執行另外的程式,clone的用途
用于有選擇地設定父子行程之間哪些資源需要共享,哪些資源需要副本拷貝,
@SvenAugustus (https://my.oschina.net/langxSpirit)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/84845.html
標籤:Linux
上一篇:httpd(一)之Web服務概述
下一篇:行程監控類命令
