最简单的epoll的使用范例 : 监听 标准输入 ,并将数据回显到终端

时间:2021-08-08 05:25:51

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

#ifndef MAX_LEN
#define MAX_LEN 256
#endif
#define EPOLL_SIZE  1000
int     main(int atgc ,char **argv)
{
    int     fd = 0;
    int     len = 0;
    int     nfds = 0;
    int     index = 0;
    char    buf[MAX_LEN] = {0};
    struct  epoll_event ev;
    struct  epoll_event event[EPOLL_SIZE];

//create a epoll object
    if(-1==(fd=epoll_create(EPOLL_SIZE))){
        perror("create epoll object error:");
        return  -1;
    }
    
    //add a file descriptor which need to be listened
    ev.events = EPOLLIN | EPOLLET;
    ev.data.fd= STDIN_FILENO;
    epoll_ctl(fd,EPOLL_CTL_ADD,STDIN_FILENO,&ev);
    
    //begin to listen the file descriptor
    while(1){
        nfds = epoll_wait(fd,event,1000,-1);
        if(nfds == -1){
            perror("epoll_wait:");
            return  -1;
        }
        for(index = 0 ; index < nfds ; index++){
            if(event[index].events == EPOLLIN){
                len = read(event[index].data.fd,buf,sizeof(buf));
                buf[len] = '\0';
                printf("buf = %s\n",buf);
            }        
        }
    }

return  EXIT_SUCCESS;
}