其他分享
首页 > 其他分享> > 尝鲜select多路复用

尝鲜select多路复用

作者:互联网

尝鲜select多路复用

问题:

如何增强服务端能力,同时支持多个客户端?

Linux的设计哲学

一切皆文件

Linux文件操作编程模式

#include <stdio.h>
#include <unistd.h>

int main(void)
{
    int iofd = 0;
    int len = 0;
    char str[] = "Titai,soft\n";

    write(iofd, str, sizeof(str));

    len = read(0, str, 5);

    str[len] = '\0';

    printf("%s\n",str);

    return 0;
}

事件相关函数的分类

神奇的selec()函数

int select(int maxfd,
          fd_set* readset,
          fd_set* writeset,
          fd_set* exceotset,
          const struct timeval* timeout);

select()函数的使用步骤

幻灯片12

select()相关数据类型及操作

fd0fd1fd2fd3
0110
FD_ZERO(fd_set* fdset);//将fd_set变量的所有位设置为0
FD_SET(int fd,fd_set* fdset);//在fd_set中指定需要监听的fd
FD_CLR(int fd, fd_set* fdset);//在fd_set中剔除fd,不再监听
FD_ISSET(int fd, fd_set* fdset);//在fd_set查看是否包含fd

代码示例

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <malloc.h>

int main(void)
{
    char s[] = "hello world\n";
    fd_set reads = {0};
    fd_set tmps = {0};
    int iofd = 0;
    struct timeval timeout = {0};
    int r = -1;
    int len = 0;

    FD_ZERO(&reads);
    FD_SET(iofd, &reads);

    while( 1 )
    {
        tmps = reads;

        timeout.tv_sec = 0;
        timeout.tv_usec = 10*1000;

        r = select(1, &tmps, 0, 0, &timeout);
        if(r > 0)
        {
            len = read(1, s, sizeof(s));
            s[len] = 0;
            printf("s[]:%s\n",s);
        }
        else if( r == 0)
        {
            //so something
            static int count = 0;
            usleep(10 * 1000);
            count++;

            if(count > 100)
            {
                printf("do something else\n");
                count = 0;
            }
        }
        else
        {
            break;
        }

    }
    return 0;
}

标签:set,多路复用,int,尝鲜,len,fd,include,select
来源: https://blog.csdn.net/LangLang_2020/article/details/122153989