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;
        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);
                }

        }
}



//注意 epoll_data結構體是個聯合體

typedef union epoll_data {
    void *ptr;
    int fd;
    __uint32_t u32;
    __uint64_t u64;
} epoll_data_t;

struct epoll_event {
    __uint32_t events;      /* Epoll events */
    epoll_data_t data;      /* User data variable */
};