I/O复用——poll(二)

poll函数

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <poll.h>  
  2. int poll(struct pollfd *fdarray,unsigned long nfds,int timeout);  
  3. /***** 返回,准备好描述字的个数,0---超时,-1---出错******/  
第一个参数是指向一个结构数组第一个元素的指针,每个数组元素都是一个pollfd结构,它规定了为测试一给定的描述字fd的一些条件。
[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. struct pollfd{  
  2.      int fd;  
  3.      short events;  
  4.      short  revents;  
  5. };  
要测试的条件由成员events规定,函数在相应的revents成员中返回的描述字的状态。(每个描述字有两个变量,一个为调用值,另一个为结果,一词避免使用值-结果参数)。这两个成员中的每一个都由指定某个条件的一位或者多为组成。下图列出了用于指定标志events并测试标志revents的一些常值

下面给出了一段使用poll监听套接口的代码

/* include fig02 */  
    for ( ; ; ) {  
        nready = Poll(client, maxi+1, INFTIM);  
  
        if (client[0].revents & POLLRDNORM) {   /* new client connection */  
            clilen = sizeof(cliaddr);  
            connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);  
#ifdef  NOTDEF  
            printf("new client: %s\n", Sock_ntop((SA *) &cliaddr, clilen));  
#endif  
  
            for (i = 1; i < OPEN_MAX; i++)  
                if (client[i].fd < 0) {  
                    client[i].fd = connfd;  /* save descriptor */  
                    break;  
                }  
            if (i == OPEN_MAX)  
                err_quit("too many clients");  
  
            client[i].events = POLLRDNORM;  
            if (i > maxi)  
                maxi = i;               /* max index in client[] array */  
  
            if (--nready <= 0)  
                continue;               /* no more readable descriptors */  
        }  
  
        for (i = 1; i <= maxi; i++) {    /* check all clients for data */  
            if ( (sockfd = client[i].fd) < 0)  
                continue;  
            if (client[i].revents & (POLLRDNORM | POLLERR)) {  
                if ( (n = read(sockfd, buf, MAXLINE)) < 0) {  
                    if (errno == ECONNRESET) {  
                            /*4connection reset by client */  
#ifdef  NOTDEF  
                        printf("client[%d] aborted connection\n", i);  
#endif  
                        Close(sockfd);  
                        client[i].fd = -1;  
                    } else  
                        err_sys("read error");  
                } else if (n == 0) {  
                        /*4connection closed by client */  
#ifdef  NOTDEF  
                    printf("client[%d] closed connection\n", i);  
#endif  
                    Close(sockfd);  
                    client[i].fd = -1;  
                } else  
                    Writen(sockfd, buf, n);  
  
                if (--nready <= 0)  
                    break;              /* no more readable descriptors */  
            }  
        }  
    }  
}  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值