I/O multiplexing (select)

I. Introduction

        IO multiplexing technology means that the process notifies the kernel to monitor one or more specified IO events. When an IO event occurs, the kernel notifies the wake-up process. It is generally used in scenarios where a process needs to monitor and process multiple IO events at the same time. Compared with multi-process or multi-thread methods, using IO multiplexing technology does not need to create multiple processes or threads, reducing system overhead.

        This article will introduce the usage of the select function, which allows the process to notify the kernel to monitor multiple IO events, and wake up the process when the event occurs or the set timeout time arrives.
 

Two. select

Function prototype:

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

Parameter Description:

nfds: The largest file descriptor among all monitored file descriptors plus one

readfds: A collection of file descriptors listening for readable events

writefds: A collection of file descriptors listening for writable events

exceptfds: A collection of file descriptors that monitor exception events

        readfds, writefds, exceptfds represent the collection of read, write, and exception events respectively. You can directly use fd_set to create an fd collection variable, use FD_ZERO to clear the collection, use FD_SET to add the specified fd to the collection, and use FD_CLR to delete the specified fd from the collection , use FD_ISSET to judge whether the specified fd is in the set. If you don't care about the corresponding event, you can directly pass NULL when calling this function. The prototypes of FD_ZERO, FD_SET, FD_CLR, and FD_ISSET are as follows:

void FD_ZERO(fd_set *fdset);

void FD_SET(int fd, fd_set *fdset);

void FD_CLR(int fd, fd_set *fdset);

int FD_ISSET(int fd, fd_set *fdset); 

timeout: Timeout time, the structure of timeval is as follows.

struct timeval {
    long tv_sec;   // seconds
    long tv_usec;  // microseconds
};

        When timeout is set to NULL, it means to wait until at least one event occurs before returning.

        When timeout is set to a timeout greater than 0, it means waiting for at least one event to occur before returning, but it will return even if there is no event when the timeout is reached.

        When timeout is set to 0, the timeout (not NULL) means return immediately after checking, that is, the way of polling.

Return value description:

If successful, return the number of events generated in the listener event collection, for example, listen to 3 readable events, 3 writeable events, 3 abnormal events, 1 readable event, 1 writable event, 2 abnormal event, the return value is 4.

On failure, -1 is returned and errno is set.

Guess you like

Origin blog.csdn.net/weixin_38102771/article/details/123179962