相对于select来说,poll 也是在指定时间内论询一定数量的文件描述符,来测试其中是否有就绪的,不过,poll 提供了一个易用的方法,来实现 i/o 复用。

声明如下:

       #include <poll.h>

       int poll(struct pollfd *fds, nfds_t nfds, int timeout);

  其中,struct pollfd 定义为:

           struct pollfd {
int fd; /* file descriptor */
short events; /* requested events */
short revents; /* returned events */
};

  fd 为文件描述符,events 告诉poll 监听fd 上哪些事件,它是一系列事件按位或。revents 由内核修改,来通知应用程序fd 上实际上发生了哪些事件。

nfds 为监听事件集合fds的大小

timeout 为poll的超时时间,单位毫秒。timeout 为-1时,poll永远阻塞,直到有事件发生。timeout为0时,poll立即返回。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <poll.h>
#include <errno.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h> #include <map>
#include <string> using namespace std; #define BUFSIZE 10
#define CLIENTSIZE 100 int createSocket()
{
struct sockaddr_in servaddr;
int listenfd = -1; if (-1 == (listenfd = socket(PF_INET, SOCK_STREAM, 0)))
{
fprintf(stderr, "socket: %d, %s\n", errno, strerror(errno));
exit(1);
} int reuseaddr = 1;
if (-1 == setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr)))
{
fprintf(stderr, "setsockopt: %d, %s\n", errno, strerror(errno));
exit(1);
} memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = PF_INET;
servaddr.sin_port = htons(8008);
inet_pton(PF_INET, "0.0.0.0", &servaddr.sin_addr); if (-1 == bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)))
{
fprintf(stderr, "bind: %d, %s\n", errno, strerror(errno));
exit(1);
} if (-1 == listen(listenfd, 5))
{
fprintf(stderr, "listen: %d, %s\n", errno, strerror(errno));
exit(1);
} return listenfd;
} int setnoblock(int fd)
{
int oldopt = fcntl(fd, F_GETFL);
int newopt = oldopt | O_NONBLOCK;
fcntl(fd, F_SETFL, newopt);
return oldopt;
} int main()
{
struct pollfd fds[CLIENTSIZE];
int listenfd = createSocket(); map<int, string> mapdata; fds[0].fd = listenfd;
fds[0].events = POLLIN | POLLERR;
fds[0].revents = 0;
int conncount = 0; while (1)
{
int ret = poll(fds, conncount + 1, -1);
if (ret < 0)
{
fprintf(stderr, "poll: %d, %s\n", errno, strerror(errno));
exit(1);
} for (int i = 0; i < conncount + 1; i++)
{
// 客户端关闭,或者错误。错误的原因是由于客户端关闭导致的,这里一并处理
if ((fds[i].revents & POLLRDHUP) || (fds[i].revents & POLLERR))
{
int fd = fds[i].fd;
fds[i] = fds[conncount];
i--;
conncount--;
mapdata.erase(fd);
close(fd);
printf("delete connection: %d\n", fd);
}
// 新的连接
else if ((fds[i].fd == listenfd) && (fds[i].revents & POLLIN))
{
struct sockaddr_in client;
socklen_t lenaddr = sizeof(client);
int conn = -1; if (-1 == (conn = accept(listenfd, (struct sockaddr*)&client, &lenaddr)))
{
fprintf(stderr, "accept: %d, %s\n", errno, strerror(errno));
exit(1);
}
printf("get connection %d from %s:%d\n", conn, inet_ntoa(client.sin_addr), client.sin_port);
conncount++;
setnoblock(conn);
fds[conncount].fd = conn;
fds[conncount].events = POLLIN | POLLRDHUP | POLLERR;
fds[conncount].revents = 0;
}
// 有可读数据
else if (fds[i].revents & POLLIN)
{
char buf[BUFSIZE] = {0}; int lenrecv = recv(fds[i].fd, buf, BUFSIZE-1, 0);
if (lenrecv > 0)
{
mapdata[fds[i].fd] = buf;
fds[i].events &= (~POLLIN);
fds[i].events |= POLLOUT;
}
else if (lenrecv == 0)
{
printf("------- client %d exit (not print) --------\n", fds[i].fd);
}
else
{
fprintf(stderr, "recv: %d, %s\n", errno, strerror(errno));
exit(1);
}
}
// 可写数据
else if (fds[i].revents & POLLOUT)
{
if (send(fds[i].fd, mapdata[fds[i].fd].c_str(), mapdata[fds[i].fd].size(), 0) < 0)
{
if (ECONNRESET == errno)
{
continue;
}
fprintf(stderr, "send: %d, %s\n", errno, strerror(errno));
exit(1);
}
fds[i].events &= (~POLLOUT);
fds[i].events |= POLLIN;
}
}
}
}

  

linux poll用法的更多相关文章

  1. linux curl用法详解

    linux ‍‍curl用法详解 ‍‍curl的应用方式,一是可以直接通过命令行工具,另一种是利用libcurl库做上层的开发.本篇主要总结一下命令行工具的http相关的应用, 尤其是http下载方面 ...

  2. [转载]expect spawn、linux expect 用法小记

    原文地址:expect spawn.linux expect 用法小记作者:悟世 使用expect实现自动登录的脚本,网上有很多,可是都没有一个明白的说明,初学者一般都是照抄.收藏.可是为什么要这么写 ...

  3. Linux poll机制

    1.用户空间调用(参考 poll(2) - Linux man page) int poll(struct pollfd *fds, nfds_t nfds, int timeout); it wai ...

  4. [转帖]linux lsof 用法简介

    linux lsof 用法简介 https://www.cnblogs.com/saneri/p/5333333.html 1.简介: lsof(list open files)是一个列出当前系统打开 ...

  5. linux poll 和 select

    使用非阻塞 I/O 的应用程序常常使用 poll, select, 和 epoll 系统调用. poll, select 和 epoll 本质上有相同的功能: 每个允许一个进程来决定它是否可读或者写一 ...

  6. Linux find 用法示例

    Linux中find常见用法示例 ·find   path   -option   [   -print ]   [ -exec   -ok   command ]   {} \; find命令的参数 ...

  7. linux poll 学习

    一.poll介绍 函数原型: #include <poll.h> int poll(struct pollfd *fds, nfds_t nfds, int timeout); struc ...

  8. linux gksu用法

    apt-get install gksu gksu是linux下图形化的su/sudo工具 sudo 用来执行命令行(CLI)程序 gksu 用来执行图形的(GUI)程序 GUI = Graphica ...

  9. linux exec用法总结

    Linux中exec的用法总结 先总结一个表: exec命令 作用 exec ls 在shell中执行ls,ls结果显示结束后不返回原来的的目录中,而是/(根目录) exec <file 将fi ...

随机推荐

  1. Sharepoint2010新建一个用户的方法

    最近在做关于SharePoint的相关开发,在开发中需要用到测试用户进行相关权限的测试,所以就需要创建一个新的用户进行,但是在网上找了很久都没有找到关于创建一个新用户的资料,最后终于在http://w ...

  2. Python数据类型及常用操作

    Python字符串类型 1.用途: 用来记录有描述性的状态.比如:人名,地址等. 2.定义方式: 创建字符串非常简单,在‘ ’,“ ”,‘’‘ ’‘’内一填写一系列的字符例如:msg='hello' ...

  3. 【起航计划 017】2015 起航计划 Android APIDemo的魔鬼步伐 16 App->Alarm->Alarm Controller Alarm事件 PendingIntent Schedule AlarmManager

    Alarm Controller演示如何在Android应用中使用Alarm事件,其功能和java.util.Timer ,TimerTask类似.但Alarm可以即使当前应用退出后也可以做到Sche ...

  4. MySQL入门很简单: 3 操作数据库

    登陆:mysq -u root -p 0409 1). 创建, 删除数据库 SHOW DATABASES; 显示已经存在的数据率 CREATE DATABASES 数据库名: 创建数据库 DROP D ...

  5. java 内存举例

    1. java内存的主要划分 2.  OOTest02.java 的内存划分 public class OOTest02{ public static void main(String[] args) ...

  6. C4C和Outlook的集成

    从C4C系统下载Outlook的Addin, 安装之后,会在Outlook里看见一个新的面板: 点击Log On登录: 如果需要的话,在Settings里设置proxy. 登录之后,即可立即在outl ...

  7. QT Creater 配色方案及下载

    打开QT Creater的工具--选项--文本编辑器--字体和颜色,复制一份配色方案:Vim (dark) ->Vim (dark) (copy) 更改想更改的任何内容的配色.其中,修改后的文件 ...

  8. 【转】Android的setTag

    前言 首先我们要知道setTag方法是干什么的,SDK解释为 Tags Unlike IDs, tags are not used to identify views. Tags are essent ...

  9. c#中的 MessageBox 弹出提示框的用法

    MessageBox.Show(<字符串str> Text, <字符串str> Title, <整型int> nType,MessageBoxIcon); 例:Me ...

  10. 基于建模的视觉定位(SFM-Based Positioning)

    具体方法来自我参与的这篇journal: Vision-Based Positioning for Internet-of-Vehicles, IEEE Transactions on Intelli ...