I/O多路复用之select、poll、epoll

目录

1、select

1.1、fd_set结构体声明

1.2、结构体timeval的声明

1.3、select函数声明

1.4、select实例

2、poll

2.1、poll的声明

2.2、event参数

2.3、poll实例

3、epoll

3.1、epoll定义

3.2、 epoll实例


1、select

1.1、fd_set结构体声明

/* /usr/include/x86_64-linux-gnu/bits/typesizes.h */
#define __FD_SETSIZE             1024

/* /usr/include/x86_64-linux-gnu/sys/select.h */
#define __NFDBITS    (8 * (int) sizeof (__fd_mask))

/* /usr/include/x86_64-linux-gnu/sys/select.h */
/* The fd_set member is required to be an array of longs.  */
typedef long int __fd_mask;

/* fd_set for select and pselect.  */
typedef struct
  {
    /* XPG4.2 requires this member name.  Otherwise avoid the name
       from the global namespace.  */
#ifdef __USE_XOPEN
    __fd_mask fds_bits[__FD_SETSIZE / __NFDBITS];
# define __FDS_BITS(set) ((set)->fds_bits)
#else
    __fd_mask __fds_bits[__FD_SETSIZE / __NFDBITS];
# define __FDS_BITS(set) ((set)->__fds_bits)
#endif
  } fd_set;

1.2、结构体timeval的声明

/* /usr/include/x86_64-linux-gnu/asm/posix_types_x32.h */
typedef long long __kernel_long_t;

/* /usr/include/asm-generic/posix_types.h */
typedef __kernel_long_t  __kernel_time_t;
typedef __kernel_long_t  __kernel_suseconds_t;

/* /usr/include/linux/time.h */
struct timeval {
        __kernel_time_t         tv_sec;         /* seconds */
        __kernel_suseconds_t    tv_usec;        /* microseconds */
};

1.3、select函数声明

/* Check the first NFDS descriptors each in READFDS (if not NULL) for read
   readiness, in WRITEFDS (if not NULL) for write readiness, and in EXCEPTFDS
   (if not NULL) for exceptional conditions.  If TIMEOUT is not NULL, time out
   after waiting the interval specified therein.  Returns the number of ready
   descriptors, or -1 for errors.

   This function is a cancellation point and therefore not marked with
   __THROW.  */
/*
    __nfds:        监控的文件描述符集里最大文件描述符加1,因为此参数会告诉内核检测前多少个文件描述符的状态
    __readfds:    被监控的读数据到达的文件描述符集合,传入传出参数
    __writefds:   被监控的有写数据到达的文件描述符集合,传入传出参数
    __exceptfds:  被监控的有异常数据到达的文件描述符集合,传入传出参数
    __restrict __timeout:    
               定时阻塞监控时间,3种情况
                1.NULL,永远等下去
                2.设置timeval,等待固定时间
                3.设置timeval里时间均为0,检查描述字后立即返回,轮询
*/
extern int select (int __nfds, fd_set *__restrict __readfds,
                   fd_set *__restrict __writefds,
                   fd_set *__restrict __exceptfds,
                   struct timeval *__restrict __timeout);

/* /usr/include/x86_64-linux-gnu/bits/select.h */
#define __FD_SET(d, set) \
  ((void) (__FDS_BITS (set)[__FD_ELT (d)] |= __FD_MASK (d)))
#define __FD_CLR(d, set) \
  ((void) (__FDS_BITS (set)[__FD_ELT (d)] &= ~__FD_MASK (d)))
#define __FD_ISSET(d, set) \
  ((__FDS_BITS (set)[__FD_ELT (d)] & __FD_MASK (d)) != 0)
# define __FD_ZERO(fdsp) \
  do {                                                                        \
    int __d0, __d1;                                                           \
    __asm__ __volatile__ ("cld; rep; " __FD_ZERO_STOS                         \
                          : "=c" (__d0), "=D" (__d1)                          \
                          : "a" (0), "0" (sizeof (fd_set)                     \
                                          / sizeof (__fd_mask)),              \
                            "1" (&__FDS_BITS (fdsp)[0])                       \
                          : "memory");                                        \
  } while (0)



/* /usr/include/x86_64-linux-gnu/sys/select.h */
#define      FD_SET(fd, fdsetp)      __FD_SET (fd, fdsetp)   //把文件描述符集合fdsetp里fd位置1
#define      FD_CLR(fd, fdsetp)      __FD_CLR (fd, fdsetp)   //把文件描述符集合fdsetp里fd位置为0
#define      FD_ISSET(fd, fdsetp)    __FD_ISSET (fd, fdsetp)  //fd是否在fdset中
#define      FD_ZERO(fdsetp)         __FD_ZERO (fdsetp)  //把文件描述符集合里所有位清0

1.4、select实例

/*================================================================
 *   Copyright (C) 2021 baichao All rights reserved.
 *
 *   文件名称:select_server.cpp
 *   创 建 者:baichao
 *   创建日期:2021年02月02日
 *   描    述:
 *
 ================================================================*/

#include 
#include 
#include 
#include 
#include 
#include 

class SelectServer
{
    public:
        SelectServer(std::string ip,int port)
        {
            memset(&serv_addr, 0, sizeof(serv_addr));  //每个字节都用0填充
            serv_addr.sin_family = AF_INET;  //使用IPv4地址
            serv_addr.sin_addr.s_addr = inet_addr(ip.c_str());  //具体的IP地址
            serv_addr.sin_port = htons(port);  //端口
            serv_addr_len = sizeof(serv_addr);

            listen_fd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
            if(listen_fd < 3)
            {
                std::cout<<"Socket error"< max_fd)
                max_fd = client_fd;
            return client_fd;
        }

        int Run()
        {
            max_fd = listen_fd;
            FD_ZERO(&master_set);
            FD_SET(listen_fd,&master_set);

            while(1)
            {
                FD_ZERO(&working_set);
                memcpy(&working_set,&master_set,sizeof(master_set));

                timeout.tv_sec = 20;
                timeout.tv_usec = 0;

                int num = select(max_fd + 1,&working_set,NULL,NULL,&timeout);

                if(num < 0)
                    return -1;

                int fd_isset_flag = FD_ISSET(listen_fd,&working_set);
                std::cout<<"fd_isset_flag:"<Bind();
    selectServer->Listen();
    selectServer->Run();
    return 0;
}

 

/*================================================================
 *   Copyright (C) 2021 baichao All rights reserved.
 *
 *   文件名称:select_client.cpp
 *   创 建 者:baichao
 *   创建日期:2021年02月01日
 *   描    述:
 *
 ================================================================*/

#include   // sockaddr_in
#include    // socket
#include   // socket
#include
#include
#include
#include
#include
#include
#include
#include

#define BUFFER_SIZE 1024

class SelectClient
{
    private:
        struct sockaddr_in server_addr;
        socklen_t server_addr_len;
        int fd;
    public:
        SelectClient(std::string ip,int port);
        ~SelectClient();
        void Connect();
        void Send(std::string str);
        std::string Recv();
};

SelectClient::SelectClient(std::string ip, int port)
{
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    if(inet_pton(AF_INET, ip.c_str(), &server_addr.sin_addr) == 0)
    {
        std::cout << "Server ip address error!";
        exit(1);
    }
    server_addr.sin_port = htons(port);
    server_addr_len = sizeof(server_addr);
    // create socket
    fd = socket(AF_INET, SOCK_STREAM, 0);
    if(fd < 0)
    {
        std::cout << "Create socket failed!";
        exit(1);
    }
}

SelectClient::~SelectClient()
{
    close(fd);
}

void SelectClient::Connect()
{
    std::cout << "Connecting......" << std::endl;
    if(connect(fd, (struct sockaddr*)&server_addr, server_addr_len) < 0)
    {
        std::cout << "Can not connect to cerver IP!";
        exit(1);
    }
    std::cout << "Connect to server success." << std::endl;
}

void SelectClient::Send(std::string str)
{
    int head_length = str.size()+1;   // 注意这里需要+1
    int ret1 = send(fd, &head_length, sizeof(head_length), 0);
    int ret2 = send(fd, str.c_str(), head_length, 0);
    if(ret1 < 0 || ret2 < 0)
    {
        std::cout << "Send message failed!";
        exit(1);
    }
}

int main()
{
    SelectClient client("127.0.0.1",11230);
    client.Connect();
    while(1)
    {
        std::string msg;
        getline(std::cin, msg);
        if(msg == "exit")
            break;
        client.Send(msg);
    }
    return 0;
}

I/O多路复用之select、poll、epoll_第1张图片

 I/O多路复用之select、poll、epoll_第2张图片

2、poll

2.1、poll的声明

/* /usr/include/x86_64-linux-gnu/sys/poll.h */

/* Type used for the number of file descriptors.  */
typedef unsigned long int nfds_t;

/* Data structure describing a polling request.  */
struct pollfd
  {
    int fd;                     /* File descriptor to poll.  */
    short int events;           /* Types of events poller cares about.  */
    short int revents;          /* Types of events that actually occurred.  */
  };

/* Poll the file descriptors described by the NFDS structures starting at
   FDS.  If TIMEOUT is nonzero and not -1, allow TIMEOUT milliseconds for
   an event to occur; if TIMEOUT is -1, block until an event occurs.
   Returns the number of file descriptors with events, zero if timed out,
   or -1 for errors.

   This function is a cancellation point and therefore not marked with
   __THROW.  */
/*
该poll()函数返回__fds集合中就绪的读、写,或出错的描述符数量,返回0表示超时,返回-1表示出错
__fds:一个struct pollfd类型的数组,用于存放需要检测的socket描述符,并且调用poll函数后__fds数组不会被清空
__nfds:__fds中描述符的总数量
timeout:调用poll函数阻塞的超时时间,单位毫秒
*/
extern int poll (struct pollfd *__fds, nfds_t __nfds, int __timeout);

2.2、event参数

events域中请求的任何事件都可能在revents域中返回。合法的事件如下:

/* Event types that can be polled for.  These bits may be set in `events'
   to indicate the interesting event types; they will appear in `revents'
   to indicate the status of the file descriptor.  */
#define POLLIN          0x001           /* There is data to read.  */
#define POLLPRI         0x002           /* There is urgent data to read.  */
#define POLLOUT         0x004           /* Writing now will not block.  */

#if defined __USE_XOPEN || defined __USE_XOPEN2K8
/* These values are defined in XPG4.2.  */
# define POLLRDNORM     0x040           /* Normal data may be read.  */
# define POLLRDBAND     0x080           /* Priority data may be read.  */
# define POLLWRNORM     0x100           /* Writing now will not block.  */
# define POLLWRBAND     0x200           /* Priority data may be written.  */
#endif

#ifdef __USE_GNU
/* These are extensions for Linux.  */
# define POLLMSG        0x400
# define POLLREMOVE     0x1000
# define POLLRDHUP      0x2000
#endif

/* Event types always implicitly polled for.  These bits need not be set in
   `events', but they will appear in `revents' to indicate the status of
   the file descriptor.  */
#define POLLERR         0x008           /* Error condition.  */
#define POLLHUP         0x010           /* Hung up.  */
#define POLLNVAL        0x020           /* Invalid polling request.  */
常量 说明
POLLIN 普通或优先级带数据可读
POLLRDNORM 普通数据可读
POLLRDBAND 优先级带数据可读
POLLPRI 高优先级数据可读
POLLOUT 普通数据可写
POLLWRNORM 普通数据可写
POLLWRBAND 优先级带数据可写
POLLERR 发生错误
POLLHUP 发生挂起
POLLNVAL 描述字不是一个打开的文件

当需要监听多个事件时,使用POLLIN | POLLRDNORM设置 events 域;当poll调用之后检测某事件是否就绪时,fds[i].revents & POLLIN进行判断。

2.3、poll实例

/*================================================================
 *   Copyright (C) 2021 baichao All rights reserved.
 *
 *   文件名称:poll_server.cpp
 *   创 建 者:baichao
 *   创建日期:2021年02月20日
 *   描    述:
 *
 ================================================================*/

#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define MAXFD 1024

class PollServer
{
    public:
        PollServer(std::string ip,int port)
        {
            memset(&serv_addr, 0, sizeof(serv_addr));  //每个字节都用0填充
            serv_addr.sin_family = AF_INET;  //使用IPv4地址
            serv_addr.sin_addr.s_addr = inet_addr(ip.c_str());  //具体的IP地址
            serv_addr.sin_port = htons(port);  //端口
            serv_addr_len = sizeof(serv_addr);

            listen_fd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
            if(listen_fd < 3)
            {
                std::cout<<"Socket error"<= 0)
                {
                    close(fds[i].fd);
                }
            }
        }


        int Bind()
        {
            if( bind(listen_fd,(struct sockaddr*) &serv_addr,serv_addr_len) == -1)
            {
                std::cout<<"Server bind failed"< nfds ? i : nfds;

            return client_fd;
        }

        int Run()
        {
            fds[0].fd = listen_fd;
            fds[0].events = POLLIN;
            nfds = 0;

            for(int i = 1; i < MAXFD; ++i)
                fds[i].fd = -1;

            while(1)
            {

                int num  = poll(fds,nfds+1,-1);

                if(num < 0)
                    return -1;

                if(fds[0].revents & POLLIN)
                    Accept();     //检测到监听的fd有消息到达,所以创建一个新的客户端fd
                else
                    Recv(num);
            }
        }
        int Recv(int num)
        {
            for(int i = 0; i <= MAXFD; ++i)
            {
                if(fds[i].revents & POLLIN)
                {
                    bool isCloseConn = false;

                    int head_length;
                    recv(fds[i].fd,&head_length,sizeof(head_length),0);
                    char *buffer = new char[head_length];
                    bzero(buffer,head_length);

                    int total = 0;
                    while(total < head_length)
                    {
                        int len = recv(fds[i].fd,buffer+total,head_length - total,0);
                        if(len < 0)
                        {
                            std::cout<<"Recv error"<Bind();
    pollServer->Listen();
    pollServer->Run();
    return 0;
}

 

I/O多路复用之select、poll、epoll_第3张图片

I/O多路复用之select、poll、epoll_第4张图片

3、epoll

3.1、epoll定义

/* Valid opcodes ( "op" parameter ) to issue to epoll_ctl().  */
#define EPOLL_CTL_ADD 1 /* Add a file descriptor to the interface.  */
#define EPOLL_CTL_DEL 2 /* Remove a file descriptor from the interface.  */
#define EPOLL_CTL_MOD 3 /* Change file descriptor epoll_event structure.  */


typedef union epoll_data
{
  void *ptr;
  int fd;
  uint32_t u32;
  uint64_t u64;
} epoll_data_t;

struct epoll_event
{
  uint32_t events;      /* Epoll events */
  epoll_data_t data;    /* User data variable */
} __EPOLL_PACKED;


/* Creates an epoll instance.  Returns an fd for the new instance.
   The "size" parameter is a hint specifying the number of file
   descriptors to be associated with the new instance.  The fd
   returned by epoll_create() should be closed with close().  */
extern int epoll_create (int __size) __THROW;

/* Manipulate an epoll instance "epfd". Returns 0 in case of success,
   -1 in case of error ( the "errno" variable will contain the
   specific error code ) The "op" parameter is one of the EPOLL_CTL_*
   constants defined above. The "fd" parameter is the target of the
   operation. The "event" parameter describes which events the caller
   is interested in and any associated user data.  */
extern int epoll_ctl (int __epfd, int __op, int __fd,
                      struct epoll_event *__event) __THROW;

/* Wait for events on an epoll instance "epfd". Returns the number of
   triggered events returned in "events" buffer. Or -1 in case of
   error with the "errno" variable set to the specific error code. The
   "events" parameter is a buffer that will contain triggered
   events. The "maxevents" is the maximum number of events to be
   returned ( usually size of "events" ). The "timeout" parameter
   specifies the maximum wait time in milliseconds (-1 == infinite).

   This function is a cancellation point and therefore not marked with
   __THROW.  */
extern int epoll_wait (int __epfd, struct epoll_event *__events,
                       int __maxevents, int __timeout);

struct epoll_event中的events值可以为下面枚举中定义的值

enum EPOLL_EVENTS
  {
    EPOLLIN = 0x001,    //表示对应的文件描述符可以读(包括对端SOCKET正常关闭);
#define EPOLLIN EPOLLIN
    EPOLLPRI = 0x002,   //表示对应的文件描述符有紧急的数据可读
#define EPOLLPRI EPOLLPRI
    EPOLLOUT = 0x004,   //表示对应的文件描述符可以写;
#define EPOLLOUT EPOLLOUT
    EPOLLRDNORM = 0x040, //和 EPOLLIN 相等
#define EPOLLRDNORM EPOLLRDNORM
    EPOLLRDBAND = 0x080, //优先读取的数据带(data band)
#define EPOLLRDBAND EPOLLRDBAND
    EPOLLWRNORM = 0x100, //和 EPOLLOUT 相等
#define EPOLLWRNORM EPOLLWRNORM
    EPOLLWRBAND = 0x200, //优先写的数据带(data band)
#define EPOLLWRBAND EPOLLWRBAND
    EPOLLMSG = 0x400,    //忽视
#define EPOLLMSG EPOLLMSG
    EPOLLERR = 0x008,    //assoc.fd有错误情况发生
#define EPOLLERR EPOLLERR
    EPOLLHUP = 0x010,    //assoc.fd发生挂起
#define EPOLLHUP EPOLLHUP
    EPOLLRDHUP = 0x2000, //
#define EPOLLRDHUP EPOLLRDHUP
    EPOLLWAKEUP = 1u << 29,
#define EPOLLWAKEUP EPOLLWAKEUP
    EPOLLONESHOT = 1u << 30,  //设置为 one-short 行为,一个事件(event)被拉出后,对应的fd在内部被禁用
#define EPOLLONESHOT EPOLLONESHOT
    EPOLLET = 1u << 31  
#define EPOLLET EPOLLET
  };

3.2、 epoll实例

服务端代码如下,客户端代码与select代码一样

/*================================================================
 *   Copyright (C) 2021 baichao All rights reserved.
 *   
 *   文件名称:epoll_server.cpp
 *   创 建 者:baichao
 *   创建日期:2021年02月22日
 *   描    述:
 *
 ================================================================*/

#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define BUFFER_SIZE 1024
#define EPOLLSIZE 100

class EPollServer
{
    public:
        EPollServer(std::string ip,int port)
        {
            memset(&serv_addr, 0, sizeof(serv_addr));  //每个字节都用0填充
            serv_addr.sin_family = AF_INET;  //使用IPv4地址
            serv_addr.sin_addr.s_addr = inet_addr(ip.c_str());  //具体的IP地址
            serv_addr.sin_port = htons(port);  //端口
            serv_addr_len = sizeof(serv_addr);

            listen_fd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
            if(listen_fd < 3)
            {
                std::cout<<"Socket error"<Bind();
    ePollServer->Listen();
    ePollServer->Run();
    return 0;
}

I/O多路复用之select、poll、epoll_第5张图片 

I/O多路复用之select、poll、epoll_第6张图片

你可能感兴趣的:(linux高级编程,网络编程,c++,socket,epoll)