unix下網絡編程之I/O複用(一)

什麼是I/O複用?編程

What we need is the capability to tell the kernel that we want to be notified if one or more I/O conditions are ready (i.e., input is ready to be read, or the descriptor is capable of taking more output). This capability is called I/O multiplexing and is provided by the select and poll functions. ——來自《Unix網絡編程》第三卷網絡

在不少狀況下,使用select或是poll,能夠把事件的響應交給底層操做系統來管理,當有I/O事件發生時,操做系統會通知咱們。異步

什麼時候使用I/O複用:socket

一、When a client is handling multiple descriptors (normally interactive input and a network socket), I/O multiplexing should be used. This is the scenario we described previously.async

二、It is possible, but rare, for a client to handle multiple sockets at the same time. We will show an example of this using select in Section 16.5 in the context of a Web client.ide

三、If a TCP server handles both a listening socket and its connected sockets, I/O multiplexing is normally used.this

四、If a server handles both TCP and UDP, I/O multiplexing is normally used.spa

五、If a server handles multiple services and perhaps multiple protocols, I/O multiplexing is normally used.操作系統

——來自《Unix網絡編程》第三卷orm

I/O模型

對於read而言,通常都會涉及到兩個過程:

1. Waiting for the data to be ready 
2. Copying the data from the kernel to the process

接下來的討論,會根據這兩階段的操做進行描述。

I/O一共有5大模型:

一、阻塞I/O

image

       應用進程產生一個system call ,若是內核沒有數據準備好,則會一直wait,處於阻塞,當內核數據準備好以後,將會把數據從內核再拷貝到應用進程,這一copy過程也處於阻塞狀態。

二、非阻塞I/O

image

       之因此稱做爲非阻塞I/O,就意味着當應用進程產生一個system call的時候,無論內核的數據是否準備好,都會當即返回。然後,再一次發起call,這是一個輪詢的過程。當內核數據準備好以後,即可以正常進行響應。這一過程是非阻塞的。而當數據從內核copy到應用進程的過程,仍然是阻塞,應爲要保證數據完整與一致。

三、I/O複用

image

      使用I/O複用,一個或多個 system call 阻塞於select 或是 poll,而不是阻塞與真正的調用。當內核有數據準備好的時候,會通知select或是poll,接下來,會發起真正的system call,也就是圖片中的recvfrom。以後,便會正常copy數據到應用進程。值得注意的是,I/O複用產生了兩次system call,一次select(poll),一次recvfrom。所以,若是進程只是處理單一描述字(descriptor)的話,使用I/O複用不但不會有好的效果,並且還會有額外的系統開銷,因此,I/O複用通常都用於處理多個描述字(descriptors)的狀況下。

四、信號驅動I/O

image

     咱們可使用信號驅動I/O,當有描述字準備好後,內核會產生信號來通知應用進程。信號驅動模型不一樣於上述三種,對於應用進程而言,它在等待接受數據過程當中,處於被通知狀態。這一過程,至關於一個異步操做。可是,對於內核copy數據到應用進程這一過程,應用進程仍然處於阻塞的狀態。

五、異步I/O

image

    信號驅動I/O模型中,在等待內核數據準備階段中,是一個異步的過程,而數據copy階段則是阻塞的,也就是同步的。可是對於異步I/O模型而言,這兩個階段都是異步的。也就說,當引用進程產生一個aio_read後,它會繼續執行其餘操做,整個過程不會產生任何阻塞。

「We call aio_read (the POSIX asynchronous I/O functions begin with aio_ or lio_) and pass the kernel the descriptor, buffer pointer, buffer size (the same three arguments for read), file offset (similar to lseek), and how to notify us when the entire operation is complete.」 ——來自《Unix網絡編程》第三卷

5個I/O模型的比較總結:

image

 

總結:

   在本文中,主要介紹了什麼是I/O複用,I/O複用的應用場景,已經5大I/O模型的介紹。 在下一篇博文中,會重點介紹Unix環境下select和poll的原理、實際應用以及代碼實現。

相關文章
相關標籤/搜索