[轉] linux新的API signalfd、timerfd、eventfd使用說明

來源:互聯網
上載者:User

標籤:

http://blog.csdn.net/gdutliuyun827/article/details/8460417

三種新的fd加入linux核心的的版本:

signalfd:2.6.22

timerfd:2.6.25

eventfd:2.6.22

三種fd的意義:

signalfd:傳統的處理訊號的方式是註冊訊號處理函數;由於訊號是非同步發生的,要解決資料的並發訪問,可重新進入問題。signalfd可以將信 號抽象為一個檔案描述符,當有訊號發生時可以對其read,這樣可以將訊號的監聽放到select、poll、epoll等監聽隊列中。

timerfd:可以實現定時器的功能,將定時器抽象為檔案描述符,當定時器到期時可以對其read,這樣也可以放到監聽隊列的主迴圈中。

eventfd:實現了線程之間事件通知的方式,eventfd的緩衝區大小是sizeof(uint64_t);向其write可以遞增這個計數 器,read操作可以讀取,並進行清零;eventfd也可以放到監聽隊列中,當計數器不是0時,有可讀事件發生,可以進行讀取。

三種新的fd都可以進行監聽,當有事件觸發時,有可讀事件發生。

signalfd涉及API:[cpp] view plaincopy
  1. #include <sys/signalfd.h>  
  2. int signalfd(int fd, const sigset_t *mask, int flags);  

參數fd:如果是-1則表示建立一個,如果是一個已經存在的則表示修改signalfd所關聯的訊號;

參數mask:訊號集合;

參數flag:核心版本2.6.27以後支援SFD_NONBLOCK、SFD_CLOEXEC;

成功返迴文件描述符,返回的fd支援以下操作:read、select(poll、epoll)、close

timerfd涉及的API[cpp] view plaincopy
  1. #include <sys/timerfd.h>  
  2. int timerfd_create(int clockid, int flags);  
  3. int timerfd_settime(int fd, int flags,  
  4.                     const struct itimerspec *new_value,  
  5.                     struct itimerspec *old_value);  
  6. int timerfd_gettime(int fd, struct itimerspec *curr_value);  
[cpp] view plaincopy
  1. timerfd_create:建立一個timerfd;返回的fd可以進行如下操作:read、select(poll、epoll)、close  
  2. timerfd_settime:設定timer的周期,以及起始間隔  
  3. timerfd_gettime:擷取到期時間。  
[cpp] view plaincopy
  1. 函數參數中資料結構如下:  
  2. struct timespec  
  3. {  
  4.     time_t tv_sec;                /* Seconds */  
  5.     long   tv_nsec;               /* Nanoseconds */  
  6. };  
  7.   
  8. struct itimerspec  
  9. {  
  10.     struct timespec it_interval;  /* Interval for periodic timer */  
  11.     struct timespec it_value;     /* Initial expiration */  
  12. };  
eventfd涉及API:[cpp] view plaincopy
  1. #include <sys/eventfd.h>  
  2. int eventfd(unsigned int initval, int flags);  

建立一個eventfd,這是一個計數器相關的fd,計數器不為零是有可讀事件發生,read以後計數器清零,write遞增計數器;返回的fd可以進行如下操作:read、write、select(poll、epoll)、close

 

這是三種新的fd的基本概念,接下來的幾篇會通過例子程式來說明各種fd的用法。

[轉] linux新的API signalfd、timerfd、eventfd使用說明

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.