2013-06-01 79 views
0

考慮下面的代碼片段:如何使用epoll?

#import <pthread.h> 
#import <stdio.h> 
#import <sys/epoll.h> 
#import <sys/eventfd.h> 
#import <unistd.h> 

int epollfd; 
int evntfd; 

void *function(void *arg) { 
    struct epoll_event events; 

    while(1) { 
     int c = epoll_wait(epollfd, &events, 1, -1); 

     if(c != -1) { 
      printf("%d\n", c); 
      break; 
     } 
    } 

    return NULL; 
} 

int main() { 
    evntfd = eventfd(0, 0); 

    epollfd = epoll_create(0); 

    struct epoll_event evnt = { 0 }; 
    evnt.data.fd = evntfd; 
    evnt.events = EPOLLIN | EPOLLET; 

    epoll_ctl(epollfd, EPOLL_CTL_ADD, evntfd, &evnt); 

    pthread_t thread; 
    pthread_create(&thread, NULL, &function, NULL); 

    sleep(1); 

    unsigned long int u = 7; 
    write(evntfd, &u, sizeof(unsigned long int)); 

    sleep(1); 

    return 0; 
} 

不應write()化妝epoll_wait返回比-1不同的值?當我編譯上面的代碼並運行它,沒有打印...

回答

2

我對你的代碼運行strace,並發現了一個驚喜的結果:

epoll_create(0)       = -1 EINVAL (Invalid argument) 

您epoll的文件描述符的尺寸需要大於零。這使一切都失敗了。

+0

感謝您的回答!你是對的,'epoll_create'正在返回'-1',爲什麼會發生這種情況?那麼,因爲'epoll_create'的單個參數必須大於零。因此,例如,將其從0更改爲1後,所有內容均按預期工作。 – LuisABOL