1. 程式人生 > >epoll示例(邊沿觸發)

epoll示例(邊沿觸發)

#include<stdio.h>
#include<unistd.h>
#include<sys/epoll.h>
struct t_connection
{
        int fd;
        void *(*call)(t_connection*);
};

void* f(t_connection* c)
{
        char buf[1024];
        read(c->fd, buf, 1);//這裡每次取一個字元後,epoll_wait不會被觸發
        printf("recv: %c\n", buf[0]);
}
int main()
{
        int epfd, nfds;
        struct epoll_event ev;
        struct epoll_event events[5];
        t_connection connection;
        connection.fd=STDIN_FILENO;
        connection.call = f;
        epfd = epoll_create(1);
        ev.data.ptr = (void*) &connection;
        ev.events = EPOLLIN | EPOLLET;
        epoll_ctl(epfd, EPOLL_CTL_ADD, STDIN_FILENO, &ev);
        for(;;)
        {
                nfds = epoll_wait(epfd, events, 5, -1);
                for(int i = 0; i < nfds; ++i)
                {
                        t_connection *c =(t_connection*) events[i].data.ptr;
                        c->call(c);
                }

        }
}