linux下的系統調用eventfd

 這個系統調用可以創建一個類似管道的東西,但比管道更簡單,它的讀和寫緩衝區只有8個字節,它會通過eventfd創建一個描述符fd,用於線程或進程間通信。簡單來說,就是進程A被write一個n,那麼進程B可以通過read讀到這個n,當然在使用過程中,n是A和B之間協商的一個有意義的數字。看一下網上的代碼就明白了

  1.  #include <sys/eventfd.h> 
  2. #include <unistd.h> 
  3. #include <stdio.h> 
  4. #include <stdint.h> 
  5. #include <stdlib.h> 
  6. #include <errno.h> 
  7.  
  8. #define handle_error(msg) \ 
  9.     do { perror(msg); exit(1); } while (0) 
  10.  
  11. int main( int argc, char **argv ) 
  12.     uint64_t u; 
  13.     ssize_t s; 
  14.     int j; 
  15.     if ( argc < 2 ) { 
  16.         fprintf(stderr, "input <num> in command argument"); 
  17.         exit(1); 
  18.     } 
  19.  
  20.     int efd; 
  21.     if ( (efd = eventfd(0, EFD_NONBLOCK)) == -1 ) 
  22.             handle_error("eventfd failed"); 
  23.  
  24.  
  25.     switch (fork()) { 
  26.         case 0: 
  27.             for( j = 1; j < argc; j ++ ) { 
  28.                 printf("Child writing %s to efd\n", argv[j] ); 
  29.              
  30.                 u = strtoull(argv[j], NULL, 0);  /* analogesly atoi */ 
  31.                 s = write(efd, &u, sizeof(uint64_t)); /* append u to counter */  
  32.                 if ( s != sizeof(uint64_t) ) 
  33.                     handle_error("write efd failed"); 
  34.  
  35.             } 
  36.             printf("child completed write loop\n"); 
  37.  
  38.             exit(0); 
  39.         default
  40.             sleep (2); 
  41.              
  42.             printf("parent about to read\n"); 
  43.             s = read(efd, &u, sizeof(uint64_t)); 
  44.             if ( s != sizeof(uint64_t) ) { 
  45.                 if (errno = EAGAIN) { 
  46.                     printf("Parent read value %d\n", s); 
  47.                     return 1; 
  48.                 } 
  49.                 handle_error("parent read failed"); 
  50.             } 
  51.             printf("parent read %d , %llu (0x%llx) from efd\n",  
  52.                     s, (unsigned long long)u, (unsigned long long) u); 
  53.             exit(0); 
  54.  
  55.         case -1: 
  56.             handle_error("fork "); 
  57.     } 
  58.     return 0; 

當在linux下網絡編程的時候,可以用此fd去做線程間的通信或者喚醒事件分離器(select poll epoll_wait),類似iocp的PostQueuedCompletionStatus,但請注意,此函數在2.6.22內核版本以後有效。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章