Five kinds of I/o,select

Source: Internet
Author: User

An input operation typically consists of two different stages:

1, wait for the data to be ready:

2. Copy data from the kernel to the process:

For an input operation on a socket:

1, waiting for data to arrive from the network. When all the wait packets arrive, it is copied to a buffer in the kernel.

2, the data is copied from the kernel buffer to the app process buffer.



The default state of the socket interface is blocked.

This means that when a socket call is issued that cannot be completed immediately, its process is put to sleep, waiting for the operation to complete.


Of course, it can also be set to non-blocking mode, calling a function

Fcntl (FD,F_SETFL, flag | 0_nonblock);



There are a lot of functions that we have written before (the client that is being shot back), many of which are related to blocking:

Read,write,accept,connect, etc. (client, server)


Let's take a look at the blocking scenario:

A simple recvfrom function: (Unix network programming: page:123)

Application process and the transformation between the kernel ...

Here is the reason to choose Recvfrom: For UDP, the transmission is the datagram, the data is ready to read the concept of more clear, the datagram arrives

Or the datagram did not arrive. However, for TCP, a byte stream in bytes??? It's not easy to understand ...

Also, is clear: from the application process to switch to the kernel space, and then switch back ...

The process calls the Recvfrom function, whose system call is not returned until the datagram arrives and is copied into the buffer of the application process or an error occurs .

The most common error is that the system call is interrupted by a signal. We say that the process is blocked from calling Recvfrom to the entire time it returns

, the application process begins processing the datagram after the Recvfrom successfully returns ....




1, input operation, including Read,readv,recv,recvfrom,recvmsg a total of 5 functions. If a process is on a blocked TCP socket

(the default setting) calls one of these input functions, and there is no data readable in the socket's receive buffer, the process will be put to sleep, straight

To have some data to reach. Since TCP is a byte-stream protocol, the process is awakened by the fact that as long as there is some data arriving, the data can be either a single

Byte, or it can be a complete TCP sub-section of data. If you want to wait until a fixed number of data is readable, then we can call

Our READN function either specifies the MSG_WAITALL flag.

For UDP, a datagram protocol, if the receive buffer for a blocked UDP socket is empty, the process that invokes the input function on it will

Be put to sleep until a UDP datagram arrives.

For example: For the read function, running from the application process space to run in the kernel space, a period of time before the switch will come ...


For non-blocking sockets, if the input operation cannot be satisfied (for TCP sockets that have at least one byte of data readable, for UDP

The socket has a full datagram readable), and the kernel does not return the corresponding data, then the call will immediately return a

Ewouldblock (equivalent to-1) error. If we need data, we must continue to call this function (the so-called cyclic reception

This loop reception is not blocking, thus causing a huge waste to the CPU, which is: busy waiting, want to wait for a certain amount of data, but

This data does not come up and consumes the CPU, so the I/O model is not used very often,

The value of the kernel space is then copied to the user space. Once the copy is complete, our read function returns and the returned value is not-1.


2, output operation, including Write,writev,send, SendTo and sendmsg a total of 5 functions. For a TCP socket, the kernel will be

Copies data from the buffer of the application process to the send buffer of the socket. For a blocked socket, if there is no space in its send buffer, the process

will be put into sleep until there is room. The indirect equivalent is given to the kernel and then taken out of the kernel.


For a non-blocking TCP socket, if there is no space at all in its send buffer, the output function call immediately returns a

Ewouldblock error. If there is some space in its send buffer, the return value will be the number of bytes that the kernel can copy into the buffer.

This number of bytes is also known as the insufficient count (short counts).


The UDP socket does not have a true send buffer. The kernel simply replicates the application process data and transmits it down the protocol stack, which is gradually crowned with UDP

Header and IP header . Therefore, for a blocked UDP socket (the default setting), the output function call will not be the same as the TCP socket as the original

Blocked, but may be blocked by other original


3, receives the external connection, namely the Accept function. If the Accept function is called on a blocked socket and no new connections are coming, the process

The same is put into the sleep state.

If the Accept function is called on a non-blocking socket and no new connections are available, the accept call will immediately return a

A: Ewouldblock error.



4, initiating an out-of-office connection, which is the Connect function for TCP (we know that connect can also be used for UDP, but it does not make a "real" connected

It only allows the kernel to save the IP address and port number of the peer. ), the establishment of a TCP connection involves a three-way handshake process, and

The Connect function waits until the customer receives an ACK acknowledgement for their SYN to return. This means that every connect to TCP always blocks its

Call the process at least one of the RTT times to the service.


If connect is called on a non-blocking TCP socket and the connection cannot be established immediately, then the build of the connection can still be initiated (e.g., sending

The first packet of a TCP three-way handshake, but returns a einprogress error. Note that this error differs from the one returned in the three above cases

Error



II: I/O multiplexing model


I/O multiplexing: Similar to the one we wrote earlier, the client has the Fgets function, the Write function, the read function (standard input and TCP sockets

Word. What we encounter is: When the server process is killed, the client cannot immediately shut down, blocking (on the standard input) fgets function, service

TCP sends a FIN to the client TCP correctly, but since the client process is blocking the process of reading from the standard input, it will not see

This read returns the EOF until it is read from the socket (probably for some time). In this way, our process requires a

The ability to inform the kernel beforehand, so that once the kernel discovers that one or more of the I/O conditions specified by the process is in place, it notifies the process, which is I/O multiplexing.

is supported by the two functions (select and poll)



We use: Select to manage multiple file descriptors, and once one or more of the file descriptors detects that there is data coming, select

Return, then this time when calling the Recv,read function will not block, then you can copy the data from the kernel to the user space, a

Once the copy is complete, then it can be returned, so that the blocking time here is just ahead of the Select,





II: Signal-driven I/O model


The main thing is that we use signals to let the kernel send Sigio signals when the descriptor is ready , and this is the signal-driven I/O model.


The process is this: first, we need to create a Sigio signal handler, at which point we need a system call: Sigaction

function to install a signal processing function. The system call will return immediately, and our process continues to work, which means it is not blocked when

When the datagram is ready to read, the kernel generates a Sigio signal for that process.

this time when calling the Recv,read function will not block, then you can copy the data from the kernel to the user space,

, the equivalent of pulling data from the kernel to user space through the Read function is a pull mechanism, not a kernel

The active push will come, a

Once the copy is complete, you can return to the



II: Asynchronous I/O

This I/O is most efficient and is implemented by Aio_read, which submits a request and a

Buffer (buf, Application layer), this time, even if no data arrives in the kernel, this function

Also returns immediately, once returned, the application process can handle the other processes, and basically

Implementation of asynchronous processing. If there is data coming, the kernel will automatically copy the data to the application layer

Buffer, which is the copy to the previous buf, once the copy is complete, it passes a signal (submitted to

Aio_read) to notify the application process. This time the upper program processes the data directly.


The difference between signal-driven I/O is that when the signal is received in the asynchronous I/O, the data has been assigned to completion,

has been assigned to the BUF space (the kernel has already been operated by default), has been returned to the user, and then does not need

To call Recv again, and so on, is the kernel pushed directly into the user buffer, which is a push mechanism. Effect

Rate relative to the previous pull mechanism, the efficiency should be higher ....



Three: Select function

Use the Select function to manage multiple I/O, and once one of the I/O or multiple I/O detects events that we are interested in, the Select function

Returns a value that is the number of detected events. and return those I/O events have occurred. Traverse these events, and then handle it

int select (int Nfds, fd_set *readfds, Fd_set *writefds,                  fd_set *exceptfds, struct timeval *timeout);

Intermediate three parameters: is three sets, about the second parameter (Fd_set *readfds), read the collection, if there is data readable, we detect

There is a data-readable set of interfaces that are placed in this set. Once the data is readable, select returns. Similarly: The third parameter is a writable collection,

The fourth parameter is a collection of exceptions.

Fifth parameter: Specifies the time-out, where the timeval structure is used to specify the number of seconds and microseconds for this time period.

struct timeval{       long   tv_sec;       Seconds       long   tv_usec;     microseconds}

Usually null, which means that an event must be detected before it can be returned. Of course, we can also give a time-out if in time to

Before the event has been generated, it will also return, this time the return is 0,

Select returns a failure of-1.


The first parameter: The maximum description multibyte 1 for storing into these collections. (stored in the Readset collection (1,3,8 event), Writest Collection

(4,9), Exceptset, then MAXFDP1 is 10 at the moment.


About Select: We often use the following four macros:

void  Fd_zero (fd_set  *fdset);                              Clear all bits in fdsetvoid  fd_set (int FD, fd_set *faset);                       Turn on the bit for FD in fdsetvoid fd_clr (int fd, fd_set *fdset);                       Turn off the bit for FD in Fdset;int fd_isset (int fd, fd_set *fdset);                       


Most of this article is excerpted from: Unix Network programming

Five kinds of I/o,select

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.