Linux网络编程/poll服务器

来源:互联网 发布:南京行知基地 编辑:程序博客网 时间:2024/06/08 13:36

一、编写poll服务器
对Pool服务器的了解:
这里写图片描述
pollfd结构包含了要监视的event和发生的event,不在使用select”参数-值”传递的方式,同时,pollfd并没有最大数量限制。和select函数一样,poll返回后,需要轮询pollfd来获取就绪的描述符。

 #include<stdio.h>#include<poll.h>int main(){    struct pollfd pfd;    pfd.fd = 0;    pfd.events = POLLIN;    pfd.revents = 0;    int timeout = -1;    while(1){        switch(poll(&pfd,1, timeout)){           case -1:               perror("poll");               break;           case 0:               printf("timeout...\n");               break;           default:               {                if (pfd.revents & POLLIN){                 char buf[1024];                ssize_t s = read(0, buf, sizeof(buf)-1);                if (s > 0)                {                        buf[s] = 0;                        printf("echo# %s\n", buf);                }               }             }               break;        }    }    return 0;}

运行结果:
这里写图片描述
总结:poll函数,解决文件描述符的上限问题,但是数量过大后性能也是下降;poll一次,不需要重新设置参数,pollfd结构体中一个结构体对应一个文件描述符。

原创粉丝点击