Select function Detailed Usage parse __ function

Source: Internet
Author: User
Tags readable stdin

1. Table header File

#include

#include

#include

2. Function prototypes

int select (int n,fd_set * Readfds,fd_set * writefds,fd_set * exceptfds,struct timeval * timeout);

3. Function description

Select () is used to wait for a change in the state of the file description Word. The parameter n represents the largest file descriptor plus 1, and the parameters Readfds, Writefds, and Exceptfds are called descriptive phrases that are used to return the read, write, or exception of the descriptive word. The macro below provides a way to handle these three types of phrases:

FD_CLR (INR fd,fd_set* set); Used to clear a bit of the associated FD in the phrase set

Fd_isset (int fd,fd_set *set); To test whether the bit of the associated FD in the phrase set is true

Fd_set (int fd,fd_set*set); used to set the bit of the associated FD in the phrase set

Fd_zero (Fd_set *set); used to clear all bits of the description phrase set

4. Description of the structure body

Two structures are described first:
1 struct fd_set can be understood as a set, which holds the file descriptor (filedescriptor), the file handle, which can be the common meaning 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
Empty 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.
2 struct Timeval is a commonly used structure that represents the time value, has two members, one is the number of seconds, and the other is the number of milliseconds. As shown below:

struct Timeval

{

time_t tv_sec;

time_t tv_usec;

};


5. Description of specific parameters:
1 int N: 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.
2) Fd_set*readfds is a pointer to the FD_SET structure, which should include a file descriptor, we want to monitor the read changes of these file descriptors, that is, we care if we can read the data from these files, if there is a file in this collection to read, 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.
3) Fd_set*writefds is a pointer to the FD_SET structure, which should include a file descriptor, we want to monitor the write changes of these file descriptors, that is, we are concerned about whether we can write data to these files, if there is a file in this 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.
4) Fd_set *errorfds with the above two parameters intent to monitor file error exceptions.
5) struct Timeval *timeout is the timeout for select, which is critical to make the select in three states, first, if NULL is passed in as a formal parameter, that is, 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.
6. return value

Negative value: Select Error

Positive values: Some files can be read or written or error 0: Wait timeout, no read or write files

If the parameter timeout is set to NULL, the Select () has no timeout.

7. Error code

Successful execution returns the number of changes in the state of the file descriptor, if the return 0 represents more than timeout time before the state of the descriptor changes, and returns 1 when there is an error, and the reason for the error is in errno, at which point the parameter Readfds,writefds, The values of Exceptfds and timeout become unpredictable.

EBADF file descriptor is invalid or the file is closed

Eintr This call is interrupted by a signal

The EINVAL parameter n is a negative value.

Enomem Core memory is low

8. Examples

1 Read 9 bytes of data in standard input.

Use the Select function to implement timeout judgment.

int main (int argc, char * * argv)

{

Char buf[10] = "";

Fd_set rdfds;//

struct Timeval TV; Store timeout

int ret; Return Val

Fd_zero (&rdfds); Clear Rdfds

Fd_set (1, &rdfds); Add stdin handle into Rdfds

Tv.tv_sec = 3;

Tv.tv_usec = 500;

RET = SELECT (1 + 1, &rdfds, NULL, NULL, &TV);

if (Ret < 0)

Perror ("\nselect");

else if (ret = 0)

printf ("\ntimeout");

Else

{

printf ("\nret=%d", ret);

}

if (Fd_isset (1, &rdfds))

{

printf ("\nreading");

Fread (BUF, 9, 1, stdin); Read Form stdin

}

Read (0, buf, 9); * Read from stdin */

fprintf (stdout, "%s\n", buf); * Write to STDOUT * *

Write (1, buf, strlen (BUF)); Write to stdout

printf ("\n%d\n", strlen (BUF));

return 0;

{2) Accept data from the network to write to a file.
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,&AMP;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,&AMP;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.