SELECT Fd_zero FD_ISSET__MFC

Source: Internet
Author: User
Tags readable

Fd_zero,fd_isset These are all nested words combined with Operation macros
Look at the Select function on MSDN, which is the core of the Select IO model to manage the socket IO and avoid innocent locking.
int select (int nfds,fd_set FAR *readfds, Fd_set FAR *writefds,
Fd_set FAR *exceptfds,
const struct Timeval FAR *timeout
);
The first parameter, whether it is a compatible purpose, and the last is the timeout criterion, the Select is a blocking operation of course to set the timeout event.
The next three types of fd_set parameters are used to check the readability, legibility, and the nature of the data in the case of a nested word.

Let me give you an example.
Like recv (), your thread will be blocked when no data arrives to call it. If the data doesn't come in, your thread is going to block for a long time. This is obviously not good. So select to see if the word is readable (i.e. whether there is data read)
Steps are as follows
socket s;
.....
Fd_set set;
while (1)
{
Fd_zero (&set)//To empty your set of words
Fd_set (S, &set);/join you interested in the set of words to the collection, here is a read the data of the sleeve word s
Select (0,&set,null,null,null);//Check that the sockets are readable,
In many cases, there is data (note, just a lot of things).
Is there an error in the Select and not written
if (Fd_isset (S, &set)/Check S is in this set,
{//select will update this collection to remove the unreadable sockets
Keep only the qualifying words in this set

Recv (s,...);

}
Do something here
}

The Select () function is primarily based on the Fd_set type. Fd_set (It is important to introduce) is a set of file descriptor (FD) that represents an FD (described below) for the Fd_set type, which is done with the following four macros:

Fd_set set;

Fd_zero (&set);

Fd_set (FD, &set);

FD_CLR (FD, &set);

Fd_isset (FD, &set);

In the past, a fd_set usually can only contain <32 fd (file descriptor), because Fd_set actually uses only a 32-bit vector to represent FD; now, UNIX systems typically define constants in header file <sys/select.h> fd_ SETSIZE, which is the number of descriptive words for a data type fd_set, is usually 1024, which can represent the <1024 FD. Based on Fd_set's bit vector implementations, we can again understand the four macros that operate Fd_set:

Fd_set set;

Fd_zero (&set);

Fd_set (0, &set);

FD_CLR (4, &set);

Fd_isset (5, &set);

―――――――――――――――――――――――――――――――――――――――

Note that the maximum value of FD must be <fd_setsize.

―――――――――――――――――――――――――――――――――――――――

The interface of the Select function is relatively simple:

int select (int Nfds, fd_set *readset, Fd_set *writeset, fd_set* exceptset, struct Tim *timeout);

Function:

Tests the specified FD to read. can be written. There are unusual conditions to be processed.

Parameters:

Nfds

Need to check the number of file descriptions (that is, check to Fd_set), the value should be greater than the maximum FD in the three groups of Fd_set, generally set to three groups of fd_set in the maximum FD value plus 1 (as in Readset,writeset, The largest FD in the Exceptset is 5, then nfds=6, because FD starts at 0. This value is designed to improve efficiency so that functions do not have to check all 1024 bits of fd_set.

Readset

A set of file descriptors used to check readability.

Writeset

A set of file descriptors that are used to check for the writable character.

Exceptset

A file descriptor used to check if an exception condition appears. (Note: Errors are not included in the exception conditions)

Timeout

There are three possible ways:

1. Timeout=null (blocking: Until a FD bit is set to 1 function to return)

2. The structure pointed to by the timeout is set to a Non-zero time (wait fixed time: one of the FD bits is reset to 1 or the time is exhausted, the function returns)

3. The structure pointed to by timeout, the time set to 0 (non-blocking: function check after each FD immediately return)

return value:

Returns the total number of FD with the corresponding bit remaining at 1.

Remarks:

All three groups of Fd_set will have some FD position 0, only those with readable, writable and abnormal conditions to be treated are still 1.

The process of using the Select function is typically:

Call the macro Fd_zero the specified fd_set, and then call the macro Fd_set add the FD that needs to be tested to fd_set, call the function Select to test all the FD in the Fd_set, and then use the macro fd_isset to check for an FD after the function select call Whether the corresponding bit is still 1.

The following is an example of the readability of a single file description:

int isready (int fd)

{

int RC;

Fd_set FDS;

struct Tim TV;

Fd_zero (&fds);

Fd_set (Fd,&fds);

tv.tv_sec = tv.tv_usec = 0;

rc = Select (fd+1, &fds, NULL, NULL, &TV);

if (RC < 0)//error

return-1;

Return Fd_isset (Fd,&fds)? 1:0;

}

Here's a few more complicated apps:

This code specifies the readable readability of the description of the test socket, because the socket is also using FD

UInt32 socketwait (tsocket *s,bool rd,bool wr,uint32)

{

Fd_set Rfds,wfds;

#ifdef _WIN32

TIM TV;

#else

struct Tim TV;

#endif

Fd_zero (&rfds);

Fd_zero (&wfds);

if (RD)//true

Fd_set (*s,&rfds); Add a descriptive word to test

if (WR)//false

Fd_set (*s,&wfds);

tv.tv_sec=timems/1000; Second

tv.tv_usec=timems%1000; Ms

for (;;)//If errno==eintr, test the readability of the buffer repeatedly

Switch (select (*s) +1,&rfds,&wfds,null,

(Timems==time_infinite?) NULL:&TV))//test whether there is data readable in the socket receive buffer within the specified time

{//0--Timeout, -1--error

Case 0:

return 0;

Case (-1):

if (SocketError () ==eintr)

Break

return 0; Wrong, but not eintr.

Default

if (Fd_isset (*S,&RFDS))///If S is a member of FDS returns non 0, otherwise returns 0

return 1;

if (Fd_isset (*s,&wfds))

return 2;

return 0;

};

}

Select function:
The system provides a select function to implement the multiplexing input/output model. Prototype:
#include <sys/time.h>
#include <unistd.h>
Select function:
The system provides a select function to implement the multiplexing input/output model. Prototype:
#include <sys/time.h>
#include <unistd.h>
int select (int maxfd,fd_set *rdset,fd_set *wrset,fd_set *exset,struct timeval *timeout);
Parameter MAXFD is the largest file descriptor value that needs to be monitored +1;rdset,wrset,exset corresponds to a collection of readable file descriptors that need to be detected, a collection of writable file descriptors, and a collection of exception file descriptors. The struct TIMEVAL structure is used to describe a length of time in which the function returns with a return value of 0 if the descriptor that needs to be monitored does not have an event occurrence within that time.
Fd_zero,fd_set,fd_clr,fd_isset: Parameter maxfd is the largest file descriptor value that needs to be monitored +1;rdset,wrset,exset corresponds to a collection of readable file descriptors that need to be detected, a collection of writable file descriptors, and exception file strokes The set of descriptors. The struct TIMEVAL structure is used to describe a length of time in which the function returns with a return value of 0 if the descriptor that needs to be monitored does not have an event occurrence within that time.
Fd_zero,fd_set,fd_clr,fd_isset:
Fd_zero (Fd_set *fdset); The specified file description is Fu Giuqing empty and must be initialized before the collection of file descriptors is set, and if not emptied, the result is not known because the system allocates memory space and is not normally emptied.
Fd_set (Fd_set *fdset); Used to add a new file descriptor to a collection of file descriptors.
FD_CLR (Fd_set *fdset); Used to delete a file descriptor in the file descriptor collection.
Fd_isset (int fd,fd_set *fdset) is used to test whether the specified file descriptor is in the collection.
struct TIMEVAL structure:
struct timeval{
Long Tv_sec;//second
Long Tv_usec;//minisecond
}
Timeout settings:
The null:select will remain blocked until an event occurs on a file descriptor.
0: Detects only the state of the descriptor collection and then returns immediately, without waiting for an external event to occur.
A specific time value: If no event occurs in the specified time period, the Select will timeout back.

Select function Application

Select in the socket programming is still more important, but for beginners socket people are not too fond of using Select to write programs, they are only accustomed to writing such as

Blocking programs such as Connect, accept, recv, or recvfrom (the so-called blocking mode block, as the name suggests, is when a process or a thread executes to these functions must wait

When an event occurs, if the event does not occur, the process or thread is blocked and the function cannot be returned immediately.

But using a select allows you to do non-blocking (the so-called non-blocking Non-block, where a process or thread performs this function without having to wait for the event to occur, once the execution returns, to reflect the difference in the value of the function, and if the event occurs the same way as blocking, If the event does not occur, return a code to tell the event not to occur, and the process or thread continues to execute, so the more efficient way to work the program, it can monitor the change of the file descriptor we need to monitor-read-write or abnormal.

Here is a detailed description.

The function format of select (I am talking about the Berkeley socket programming under UNIX system, and the difference under Windows, for a moment):

int select (int maxfdp,fd_set *readfds,fd_set *writefds,fd_set *errorfds,struct timeval *timeout);

Two structures are described first:

First, struct fd_set can be understood as a set, which holds the file descriptor (FileDescriptor), which is the file handle, which is what we call the common sense of the file, of course, UNIX under any Device, pipeline, FIFO, etc. are file forms, All included, so there is no doubt that a socket is a file, and the socket handle is a file descriptor.

The Fd_set collection can be manipulated by some macros, such as emptying the set Fd_zero (Fd_set *);

Adds a given file descriptor to the collection fd_set (int, fd_set *);

Deletes a given file descriptor from the collection fd_clr (int, fd_set*);

Checks whether the specified file descriptor in the collection can read and write Fd_isset (int, fd_set*). For a moment, illustrate.

Second, struct timeval is a commonly used structure to represent time values, with two members, one for seconds and the other for subtle numbers.

To explain the parameters of a select specifically:

int MAXFDP is an integer value that refers to the range of all file descriptors in the collection, that is, the maximum value of all file descriptors plus 1, not wrong. The value of this parameter in Windows does not matter and can be set incorrectly.

Fd_set*readfds is a pointer to the FD_SET structure, which should include a file descriptor that we want to monitor for read changes to these file descriptors, that is, we care whether we can read the data from these files, if there is a file in the collection that is readable, The select returns a value greater than 0, indicating that a file is readable, and if there are no readable files, then the timeout is judged according to the timeout parameter, and if the time exceeds timeout, select returns 0, which returns a negative value if an error occurs. You can pass in a null value to indicate that you do not care about read changes to any file.

Fd_set*writefds is a pointer to the FD_SET structure, which should include a file descriptor, and we want to monitor the write changes of these file descriptors, that is, we care about whether we can write to these files, if there is a file in the collection to write, Select returns a value greater than 0, indicating that there is a file to write, if there is no writable file, then the timeout parameter to determine whether to timeout, if more than timeout time, select return 0, if an error returns a negative value. You can pass in a null value, indicating that you don't care about any file's write changes.

Fd_set *errorfds The intent of the two parameters above to monitor file error exceptions.

struct Timeval *timeout is the timeout for select, which is critical in that it allows the select to be in three states, first, if NULL is passed in as a parameter, without passing in the time structure, the select is placed in a blocking state, Be sure to wait until a file descriptor in the collection of the monitor file descriptor changes; second, if the time value is set to 0 seconds 0 milliseconds, it becomes a pure non-blocking function, regardless of whether the file descriptor changes, immediately return to continue execution, the file does not change the return of 0, there are changes to return a positive; third, The value of the timeout is greater than 0, which is the timeout for the wait, that is, the select is blocked in the timeout time and the event comes back within the timeout period, otherwise it will be returned after the timeout, and the return value is the same as above.

return value:

Negative value: Select Error positive: Some files can read or write or error 0: Wait timeout, no read or write files

After you have a select, you can write a decent web program. A simple example is to accept data from a network to write to a file.

Example:

Main ()

{

int sock;

FILE *FP;

struct Fd_set FDS;

struct Timeval timeout={3,0}; Select wait 3 seconds, 3 seconds polling, 0 to be non-blocking

Char buffer[256]={0}; 256-byte Receive buffer

/* Assume that the UDP connection has been established, the specific process does not write, simple, of course, TCP also the same, host IP and port have been given, to write the file has been opened

Sock=socket (...);

Bind (...);

Fp=fopen (...); */

while (1)

{

Fd_zero (&fds); The collection must be emptied at each loop, otherwise the descriptor changes cannot be detected

Fd_set (Sock,&fds); Add descriptor

Fd_set (Fp,&fds); Ditto

maxfdp=sock>fp?sock+1:fp+1; Descriptor Maximum plus 1

Switch (select (maxfdp,&fds,&fds,null,&timeout))//select use

{

Case-1: Exit ( -1); Select Error, exiting program

Case 0:break; Poll again

Default

if (Fd_isset (SOCK,&FDS))//test sock is readable, that is, whether there is data on the network

{

Recvfrom (sock,buffer,256,.....); /Accept Network data

if (Fd_isset (FP,&FDS))//test file is writable

Fwrite (Fp,buffer ...); /write File

Buffer empty;

}//End If break;

}//End Switch

}//end while

}//end Main

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.