Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Realizing the reuse of IO with select

Shulou Source: shulou.com Published: 2022-06-01 08:19:09 10月03日 Update

Select system calls are used to monitor changes in the state of multiple handles (file descriptors) at a time. The program stops at select and waits until one or more of the monitored handles have a state change.

Select function prototype:

Int select (int nfds, fd_set * readfds, fd_set * writefd,fd_set * exceptfds, struct timeval * timeout)

Nfds: indicates the number of file descriptor sets

Readfds: how many read events are there (called read events when there is data in this state)

Writefd: how many write events are there currently (care whether the output buffer is full)

The last structure indicates that every few seconds you wake up to do something else, which is used to set the select wait time.

The return value of the function:

Successful execution returns the number of states that have changed in the descriptor set

Return 0 indicates that the descriptor has been timeout before the state of the descriptor changes

Return-1 indicates that an error has occurred, which may be the arrival of data outside of a socket.

On the Operation of related functions of select function

FD_CLR (inr fd,fd_set* set); to clear the bit of related fd in the descriptive phrase set

FD_ISSET (int fd,fd_set * set); determine whether the file descriptor is in the current file descriptor set

FD_SET (int fd,fd_set*set); sets the descriptor to the current file descriptor set

FD_ZERO (fd_set * set); can be used to initialize a set of file descriptors

Fd_set in select model, for example: if fd_set is 1 byte and has 8 bits, then each bit can correspond to a file descriptor. If fd=1, it should be 0000 0001.

When adding fd to the select monitoring set, use an array to save the file descriptors placed in the select monitoring set. In order that after the select returns, the data stored in the array can be judged by FD_ISSET with fd_set. After returning, select will empty the previously added fd without any events, and get the fd from the array again before starting select each time.

Join them one by one.

Using select to realize TCP Communication

Server side:

1 # include 2 # include 3 # include 4 # include 5 # include 6 # include 7 # include 8 # include 9 # include 10 int fileds [64]; / / use an array to save the file descriptor 11 void Usage (const char* proc) 12 {13 printf ("Usage:%s [ip] [port]\ n", proc) in the select monitoring set; 14} 15 16 int start (int port,char* ip) 17 {18 int listen_sock=socket (AF_INET,SOCK_STREAM,0) 19 if (listen_sock

Tags: File event state function array monitor data number kernel handle multiple reuse success prototype at the same time socket byte client client overhead Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Shulou Technology Huawei Redmi Microsoft