epoll函数分析

阻塞IO和进程的多路复用。

相比select的优点:

epoll();
1.高效
2.监控无上限

 

epoll的使用:
epoll_create/epoll_creatl(创建监听池)
epoll_ctl(添加监听事件)
epoll_wait(等待事件发生)

 

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/epoll.h>
 
int main()
{  
    int fd1,fd2;
    int efd;
    struct epoll_event event;
    struct epoll_event *events;
    char c;   
    //创建fifo
    mkfifo("/tmp/fifo1",0666);
    mkfifo("/tmp/fifo2",0666);
   
    fd1 = open("/tmp/fifo1",O_RDONLY);
    fd2 = open("/tmp/fifo2",O_RDONLY);
    //创建监听池
    efd = epoll_create1(0);
    //构造监听事件,加入监听池
    event.events = EPOLLIN|EPOLLET;
    event.data.fd = fd1;
    epoll_ctl(efd,EPOLL_CTL_ADD,fd1,&event);
     
    event.events = EPOLLIN|EPOLLET;
    event.data.fd = fd2;
    epoll_ctl(efd,EPOLL_CTL_ADD,fd2,&event);
     
    int n = 0;
    events = calloc(100,sizeof(event));
    n =  epoll_wait(efd,events,100,-1);
    int i = 0;
    for(i = 0;i<n;i++)
    {
        if(events[i].events&EPOLLIN)
        {
            read(events[i].data.fd,&c,1);
            printf("file %d can be read\n",events[i].data.fd);
        }
 
        if(events[i].events&EPOLLOUT)
        {
           //处理
        }
      
        if(events[i].events&EPOLLERR)
        {
             //处理
        }
    }
    free(events);
    close(fd1);
    close(fd2);
     
}


测试1:ew1.c

 

 

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/epoll.h>

int main()
{
    int fd;
    char c='c';

    fd = open("/tmp/fifo1",O_WRONLY);
    write(fd,&c,1);
    close(fd);
    return 0;
}


测试1:ew2.c

 

 

 

 

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/epoll.h>

int main()
{
    int fd;
    char c='c';

    fd = open("/tmp/fifo2",O_WRONLY);
    write(fd,&c,1);
    close(fd);
    return 0;
}


运行epoll 程序进入阻塞状态,然后运行ew1,ew2

 

打印并退出阻塞。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值