Chapter 6 I / O multiplexing function select and poll

Capacity I / O multiplexing: if the one or more I / O conditions (e.g., input ready to be read, or can undertake descriptor more output), we were informed.

I / O multiplexing a function select and poll support.

I / O multiplexing typical applications:
A descriptor when a plurality of clients (generally input and interactive network socket) must use I / O multiplexing;.
B simultaneously processing a plurality of sets of client interfaces [. less frequent];
. C process both the TCP server listen socket, then the socket have to have processing;
. D handle both the TCP server, but also process the UDP;
. E multiple services or servers to handle multiple protocols [ For example inetd daemon].

Unix under five I / O model:
1. blocking I / O model
    of the most popular I / O model, by default, all sockets are blocked.
    System call recvfrom example, we say that the process of blocking the whole time is beginning to call recvfrom this time it returns, when the process returns an indication of success, the application process starts processing.
2. The non-blocking I / O model
    when we put a socket set to a non-blocking manner, notify the kernel: When requested I / O operations have to let the process can not be completed during sleep, do not let the process of sleep, but should return to a error.
    When an application to describe when a non-blocking sockets cycle call recvfrom, we call this process as polling polling.
3. I / O multiplexing pattern
4. The drive signal I / O model
    Use signal, let the kernel inform us when describing the character ready signal SIGIO - signal drive I / O.
5. asynchronous I / O model of
    the new 1993 version of the content Posix.1 in.

select function
This function allows a process to indicate any kernel wait for multiple events occurred in one, and only after the occurrence or after a specified time wake-up process in one or more events.

#include <SYS / select.h>
#include <SYS / time.h>
int the SELECT (int maxfdp1, fd_set * readset, fd_set * writeset, df_set exceptset *, const struct timeval * timeout);
Returns: right -> Ready n is the number of descriptor timeout -> 0, the error -> -1.
timeout: to tell the kernel to wait for either a specified set of characters described in a ready to spend much time, timeval structure to specify the number of seconds and microseconds members of the book.
timeval {struct
    Long tv_sec; / * seconds The * /
    Long tv_usec; / * microseconds * /
};
there are three possibilities:
1. wait forever: there is only a descriptive word ready for I / O only return for this, the parameters timeout is set to a null pointer;
2. waiting for a fixed time: returns a descriptor when ready I / O, but not more than the time specified timeout parameter;
3. no wait: Check the descriptor immediately after the return, which is called polling polling. For this reason, timeout member is set to 0.
readset, writeset, exceptset descriptor we want to specify kernel testing required for reading, writing and abnormal conditions.
Now only support two abnormal conditions:
1. The socket-band data arrival;
presence status 2. Control information from a pseudo-terminal has been set to the master mode to read a packet.
How readset, writeset, each parameter specifies a exceptset three or more descriptor values?
select descriptive character set, which is generally an array of integers, each number corresponding to each bit in a descriptor. For example, with 32-bit integers, the first element of the array corresponds to the descriptor of 0 to 31, the second element of the array corresponds to the descriptor 32 to 63, and so on. [One possible implementation]
void FD_ZERO (fdset the fd_set *); / * Clear All bits in fdset * /
void the FD_SET (int FD, the fd_set fdset *); / * Turn ON The 'bit in fdset for FD * /
void FD_CLR macros (int FD, the fd_set fdset *); / * Turn OFF The 'bit in fdset for FD * /
void FD_ISSET (int FD, the fd_set fdset *); / * The' bit for IS ON in fdset * FD /
Maxfdp1 parameter specifies the number of words is described in the test, which is the maximum value of descriptor to be tested is added to 1, as described word is zero.
Parameters maxfdp1 exists, the sole purpose of considering the efficiency.
Function select to change the character set by the pointer described readset, writeset, exceptset referred to. These three parameters are a value - result parameter. When we call the function, specify the character set description we are concerned, when returning, the results indicate that descriptor is ready.
Any descriptor set described unprepared cleared to 0, the corresponding bit word returned.

Descriptor is ready under what circumstances?
1. When the following four conditions is satisfied by any one, socket ready to read:
. A socket receive data bytes in the buffer is greater than the current value of the socket receive buffer is equal to the low limit. Such a read operation does not block the socket and returns a value greater than zero (i.e., ready to read the data amount of). We can use the socket set this option SO_RCVLOWAT low limit. For TCP and UDP sockets, which defaults to 1.
b. Read the other connector half closed (that is receiving the FIN TCP connection). Such read operation of the socket will not be blocked and return 0 (i.e. End Of File).
C the number of connections. listen socket is a socket and a non-zero finished.
D. There is a socket pending errors. Such read operation of the socket will not be blocked and return an error (-1), errno were arranged to clear the error condition. These errors are pending (pending errors) can also be made clear call getsockopt by specifying the socket option SO_ERROR.

These columns when any of the three conditions is met, the socket is ready to write:
a. the number of bytes transmitted socket is greater than the available space in the buffer is equal to the current value of the transmit socket buffer of low limit. For TCP and UDP socket, the default value is typically 2048.
b. Connect writing this half closed. Such a write operation to the socket will generate a signal SIGPIPE.
C. There is a socket pending errors. Such a write operation to the socket will not be blocked and return an error (-1), errno is set to clear the error condition. These errors can also be processed to obtain and cleared by the specified socket option SO_ERROR call getsockopt.

If a socket is still present in the band or band data tag, then it has an abnormal condition to be treated.

Function fileno the standard I / O file pointer to its corresponding word to describe converter. Example:
the fileno (stdin) = 0, the fileno (stdout) =. 1, the fileno (stderr) = 2

the Ping is measured length of 84 bytes for IP datagrams.

shutdown function
normally terminates a network connection method is to call close, but there are two close shutdown function limits may be avoided.
1. close the access descriptor word count by 1, only when this count is 0 Close the socket. We can inspire with shutdown normal TCP connection termination sequence (FIN by the beginning of section four points), regardless of the access count.
2. close to terminate the data transfer in both directions: read and write. Because a TCP connection is full duplex, many times we would like to inform the other end we have completed data is sent, even if that end is still a lot of data to be transmitted as well.
#include <sys / socket.h>
int shutdown (int sockfd, int howto );
Returns: OK -> 0, Error - > -1.
This function-dependent parameter values howto:
SHUT_RD
    read this half closing the connection, the data no longer accept the socket and the socket are now receiving data remaining in the buffer are discarded. The process can no longer read any line socket function. After calling this function, any data received by the TCP socket are acknowledged, but the data itself is discarded.
SHUT_WR
    closing the connection to write this half, in the case of TCP, this is called half-close (half-close). Current are transmitted transmission data left in the socket buffer, followed by the normal TCP connection termination sequence. The process can not perform any write function socket.
SHUT_RDWR
    read connection of this half and half are writing this off. Equivalent and has invoked SHUT_RD and SHUT_WR.

When a server is processing multiple clients, servers must not only blocking calls to a function related to a single customer. If so, the server will hang and refuse to provide services to other customers, this is called a denial of service denial of service type attacks.
Approach denial of service attacks:
A Use non-blocking I / O model;.
B so that each customer is served by a single thread of control;.
C operating settings for I / O timeout.

Function pselect
the invention Posix.1g
#include <SYS / in select.h>
#include <signal.h>
#include <time.h>
int the pselect (int maxfdp1, the fd_set readset *, * writeset the fd_set, the fd_set exceptset *,
        const struct the timespec timeout *, const * sygset_t the sigmask);
Returns: OK -> the number of scan ready timeout -> 0, the error -> -1.
the timespec {struct
    time_t the tv_sec; / * seconds The second * /
    logN tv_nsec; / * nanoseconds ns * /
};
the sigmask: a pointer to a signal mask.

poll function
poll and select provide similar functionality, but when it comes to the flow device, also provides additional information.
#include <poll.h>
int poll (struct * fdarray the pollfd, unsigned Long NFDs, int timeout);
Returns: OK -> Ready descriptor number, the time-out -> 0, the error -> -1
struct the pollfd {
    int fd; / * * descriptor to the Check /
    Short Events;
    revents Short; / * Events that occurred ON FD * /
};
condition to be tested by a member of a predetermined events, the function returns the appropriate word to describe the state of revents members. (There are two variables for each descriptor, a value for the call, the other is the result, thereby avoiding the use of the value - result parameter).
ndfs: fdarray number of array elements.
timeout: how long to wait before the function returns. There are three cases:
    INFTIM: wait forever; 0: return immediately, without blocking;> 0: Wait specified number of milliseconds.
If you do not care about a particular descriptor, fd members can pollfd structure is set to a negative value, so you can ignore the members of the events, and members will return revents value is set to 0.

Reproduced in: https: //www.cnblogs.com/learne/archive/2009/08/12/1544424.html

Guess you like

Origin blog.csdn.net/weixin_33757609/article/details/94255008