三種新的fd加入linux核心的的版本:
signalfd:2.6.22
timerfd:2.6.25
eventfd:2.6.22
三種fd的意義:
lsignalfd
傳統的處理訊號的方式是註冊訊號處理函數;由於訊號是非同步發生的,要解決資料的並發訪問,可重新進入問題。signalfd可以將訊號抽象為一個檔案描述符,當有訊號發生時可以對其read,這樣可以將訊號的監聽放到select、poll、epoll等監聽隊列中。
ltimerfd
可以實現定時器的功能,將定時器抽象為檔案描述符,當定時器到期時可以對其read,這樣也可以放到監聽隊列的主迴圈中。
leventfd
實現了線程之間事件通知的方式,也可以用於使用者態和核心通訊。eventfd的緩衝區大小是sizeof(uint64_t);向其write可以遞增這個計數器,read操作可以讀取,並進行清零;eventfd也可以放到監聽隊列中,當計數器不是0時,有可讀事件發生,可以進行讀取。
三種新的fd都可以進行監聽,當有事件觸發時,有可讀事件發生。
signalfd涉及API:
點擊(此處)摺疊或開啟
 #include <sys/signalfd.h> int signalfd(int fd, const sigset_t *mask, int flags);#include <sys/signalfd.h> 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
l例子
 #include <sys/signalfd.h> #include <signal.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #define handle_error(msg) \ do { perror(msg); exit(EXIT_FAILURE); } while (0) int main(int argc, char *argv[]) { sigset_t mask; int sfd; struct signalfd_siginfo fdsi; ssize_t s; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if (sigprocmask(SIG_BLOCK, &mask, NULL) == -1) handle_error("sigprocmask"); sfd = signalfd(-1, &mask, 0); if (sfd == -1) handle_error("signalfd"); for (;;) { s = read(sfd, &fdsi, sizeof(struct signalfd_siginfo)); if (s != sizeof(struct signalfd_siginfo)) handle_error("read"); if (fdsi.ssi_signo == SIGINT) { printf("Got SIGINT\n"); } else if (fdsi.ssi_signo == SIGQUIT) { printf("Got SIGQUIT\n"); exit(EXIT_SUCCESS); } else { printf("Read unexpected signal\n"); } } }#include <sys/signalfd.h> #include <signal.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #define handle_error(msg) \ do { perror(msg); exit(EXIT_FAILURE); } while (0) int main(int argc, char *argv[]) { sigset_t mask; int sfd; struct signalfd_siginfo fdsi; ssize_t s; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if (sigprocmask(SIG_BLOCK, &mask, NULL) == -1) handle_error("sigprocmask"); sfd = signalfd(-1, &mask, 0); if (sfd == -1) handle_error("signalfd"); for (;;) { s = read(sfd, &fdsi, sizeof(struct signalfd_siginfo)); if (s != sizeof(struct signalfd_siginfo)) handle_error("read"); if (fdsi.ssi_signo == SIGINT) { printf("Got SIGINT\n"); } else if (fdsi.ssi_signo == SIGQUIT) { printf("Got SIGQUIT\n"); exit(EXIT_SUCCESS); } else { printf("Read unexpected signal\n"); } } }
 
L17-L21:將感興趣的訊號加入到sigset_t中;
L24:調用signalfd,把訊號集與fd關聯起來,第一個參數為-1表示建立一個signalfd,不是-1並且是一個合法的signalfd表示向其添加新的訊號。
L29:阻塞等待訊號的發生並讀取。根據讀取的結果可以知道發生了什麼訊號。
timerfd涉及的API
 #include <sys/timerfd.h> int timerfd_create(int clockid, int flags); int timerfd_settime(int fd, int flags, const struct itimerspec *new_value,struct itimerspec *old_value); int timerfd_gettime(int fd, struct itimerspec *curr_value);#include <sys/timerfd.h> int timerfd_create(int clockid, int flags); int timerfd_settime(int fd, int flags, const struct itimerspec *new_value,struct itimerspec *old_value); int timerfd_gettime(int fd, struct itimerspec *curr_value);timerfd_create:建立一個timerfd;返回的fd可以進行如下操作:read、select(poll、epoll)、closetimerfd_settime:設定timer的周期,以及起始間隔timerfd_gettime:擷取到期時間。//函數參數中資料結構如下: struct timespec { time_t tv_sec; /* Seconds */ long tv_nsec; /* Nanoseconds */ }; struct itimerspec { struct timespec it_interval; /* Interval for periodic timer */ struct timespec it_value; /* Initial expiration */ };//函數參數中資料結構如下: struct timespec { time_t tv_sec; /* Seconds */ long tv_nsec; /* Nanoseconds */ }; struct itimerspec { struct timespec it_interval; /* Interval for periodic timer */ struct timespec it_value; /* Initial expiration */ };
 
l例子
 #include <sys/timerfd.h> #include <sys/time.h> #include <time.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> /* Definition of uint64_t */ #define handle_error(msg) \ do { perror(msg); exit(EXIT_FAILURE); } while (0) void printTime() { struct timeval tv; gettimeofday(&tv, NULL); printf("printTime: current time:%ld.%ld ", tv.tv_sec, tv.tv_usec); } int main(int argc, char *argv[]) { struct timespec now; if (clock_gettime(CLOCK_REALTIME, &now) == -1) handle_error("clock_gettime"); struct itimerspec new_value; new_value.it_value.tv_sec = now.tv_sec + atoi(argv[1]); new_value.it_value.tv_nsec = now.tv_nsec; new_value.it_interval.tv_sec = atoi(argv[2]); new_value.it_interval.tv_nsec = 0; int fd = timerfd_create(CLOCK_REALTIME, 0); if (fd == -1) handle_error("timerfd_create"); if (timerfd_settime(fd, TFD_TIMER_ABSTIME, &new_value, NULL) == -1) handle_error("timerfd_settime"); printTime(); printf("timer started\n"); for (uint64_t tot_exp = 0; tot_exp < atoi(argv[3]);) { uint64_t exp; ssize_t s = read(fd, &exp, sizeof(uint64_t)); if (s != sizeof(uint64_t)) handle_error("read"); tot_exp += exp; printTime(); printf("read: %llu; total=%llu\n",exp, tot_exp); } exit(EXIT_SUCCESS); }#include <sys/timerfd.h> #include <sys/time.h> #include <time.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> /* Definition of uint64_t */ #define handle_error(msg) \ do { perror(msg); exit(EXIT_FAILURE); } while (0) void printTime() { struct timeval tv; gettimeofday(&tv, NULL); printf("printTime: current time:%ld.%ld ", tv.tv_sec, tv.tv_usec); } int main(int argc, char *argv[]) { struct timespec now; if (clock_gettime(CLOCK_REALTIME, &now) == -1) handle_error("clock_gettime"); struct itimerspec new_value; new_value.it_value.tv_sec = now.tv_sec + atoi(argv[1]); new_value.it_value.tv_nsec = now.tv_nsec; new_value.it_interval.tv_sec = atoi(argv[2]); new_value.it_interval.tv_nsec = 0; int fd = timerfd_create(CLOCK_REALTIME, 0); if (fd == -1) handle_error("timerfd_create"); if (timerfd_settime(fd, TFD_TIMER_ABSTIME, &new_value, NULL) == -1) handle_error("timerfd_settime"); printTime(); printf("timer started\n"); for (uint64_t tot_exp = 0; tot_exp < atoi(argv[3]);) { uint64_t exp; ssize_t s = read(fd, &exp, sizeof(uint64_t)); if (s != sizeof(uint64_t)) handle_error("read"); tot_exp += exp; printTime(); printf("read: %llu; total=%llu\n",exp, tot_exp); } exit(EXIT_SUCCESS); }
 
代碼L25-L29:初始化定時器的參數,初始間隔與定時間隔。
L32:建立定時器fd,CLOCK_REALTIME:真即時間類型,修改時鐘會影響定時器;CLOCK_MONOTONIC:相對時間類型,修改時鐘不影響定時器。
L35:設定定時器的值。
L44:阻塞等待定時器到期。傳回值是未處理的到期次數。比如定時間隔為2秒,但過了10秒才去讀取,則讀取的值是5。
編譯運行:編譯時間要加rt庫(g++ -lrt timerfd.cc -o timerfd)
 [root@localhost appTest]# ./timerfd 5 2 10printTime: current time:1357391736.146196 timer startedprintTime: current time:1357391741.153430 read: 1; total=1printTime: current time:1357391743.146550 read: 1; total=2printTime: current time:1357391745.151483 read: 1; total=3printTime: current time:1357391747.161155 read: 1; total=4printTime: current time:1357391749.153934 read: 1; total=5printTime: current time:1357391751.157309 read: 1; total=6printTime: current time:1357391753.158384 read: 1; total=7printTime: current time:1357391755.150470 read: 1; total=8printTime: current time:1357391757.150253 read: 1; total=9printTime: current time:1357391759.149954 read: 1; total=10[root@localhost appTest]#
 
第一個參數5為第一次定時器到期間隔,第二個參數2為定時器的間隔,第三個參數為定時器到期10次則退出。程式運行(5+2*10)S退出。
詳細資料可以:man timerfd_create
eventfd涉及API:
 #include <sys/eventfd.h> int eventfd(unsigned int initval, int flags);#include <sys/eventfd.h> int eventfd(unsigned int initval, int flags);
 
建立一個eventfd,這是一個計數器相關的fd,計數器不為零是有可讀事件發生,read以後計數器清零,write遞增計數器;返回的fd可以進行如下操作:read、write、select(poll、epoll)、close。
這個函數會建立一個事件對象 (eventfd object), 用來實現,進程(線程)間的等待/通知(wait/notify) 機制. 核心會為這個對象維護一個64位的計數器(uint64_t)。並且使用第一個參數(initval)初始化這個計數器。調用這個函數就會返回一個新的檔案描述符(event object)。2.6.27版本開始可以按位設定第二個參數(flags)。有如下的一些宏可以使用:
lEFD_NONBLOCK
功能同open(2)的O_NONBLOCK,設定對象為非阻塞狀態,如果沒有設定這個狀態的話,read(2)讀eventfd,並且計數器的值為0 就一直堵塞在read調用當中,要是設定了這個標誌, 就會返回一個 EAGAIN 錯誤(errno = EAGAIN)。效果也如同 額外調用select(2)達到的效果。
lEFD_CLOEXEC
這個標識被設定的話,調用exec後會自動關閉檔案描述符,防止泄漏。如果是2.6.26或之前版本的核心,flags 必須設定為0。
建立這個對象後,可以對其做如下操作:
1) write: 將緩衝區寫入的8位元組整形值加到核心計數器上。
2) read: 讀取8位元組值, 並把計數器重設為0. 如果調用read的時候計數器為0, 要是eventfd是阻塞的, read就一直阻塞在這裡,否則就得到 一個EAGAIN錯誤。如果buffer的長度小於8那麼read會失敗, 錯誤碼被設定成 EINVAL。
3) poll select epoll
4) close: 當不需要eventfd的時候可以調用close關閉, 當這個對象的所有控制代碼都被關閉的時候,核心會釋放資源。 為什麼不是close就直接釋放呢, 如果調用fork 建立
進程的時候會複製這個控制代碼到新的進程,並繼承所有的狀態。
l例子
 #include <sys/eventfd.h>#include <unistd.h>#include <stdio.h>#include <stdint.h>#include <stdlib.h>#include <errno.h>#define handle_error(msg) \do { perror(msg); exit(1); } while (0)int main( int argc, char **argv ){uint64_t u;ssize_t s;5 int j;if ( argc < 2 ) {fprintf(stderr, "input in command argument");exit(1);}int efd;if ( (efd = eventfd(0, EFD_NONBLOCK)) == -1 )handle_error("eventfd failed");switch (fork()) {case 0:for( j = 1; j < argc; j ++ ) {printf("Child writing %s to efd\n", argv[j] );u = strtoull(argv[j], NULL, 0); /* analogesly atoi */s = write(efd, &u, sizeof(uint64_t));/*append u to counter */if ( s != sizeof(uint64_t) )handle_error("write efd failed");}printf("child completed write loop\n");exit(0);default:sleep (2);printf("parent about to read\n");s = read(efd, &u, sizeof(uint64_t));if ( s != sizeof(uint64_t) ) {if (errno = EAGAIN) {printf("Parent read value %d\n", s);return 1;}handle_error("parent read failed");}printf("parent read %d , %llu (0x%llx) from efd\n",s, (unsigned long long)u, (unsigned long long) u);exit(0);case -1:handle_error("fork ");}return 0;}#include <sys/eventfd.h>#include <unistd.h>#include <stdio.h>#include <stdint.h>#include <stdlib.h>#include <errno.h>#define handle_error(msg) \do { perror(msg); exit(1); } while (0)int main( int argc, char **argv ){uint64_t u;ssize_t s;5 int j;if ( argc < 2 ) {fprintf(stderr, "input in command argument");exit(1);}int efd;if ( (efd = eventfd(0, EFD_NONBLOCK)) == -1 )handle_error("eventfd failed");switch (fork()) {case 0:for( j = 1; j < argc; j ++ ) {printf("Child writing %s to efd\n", argv[j] );u = strtoull(argv[j], NULL, 0); /* analogesly atoi */s = write(efd, &u, sizeof(uint64_t));/*append u to counter */if ( s != sizeof(uint64_t) )handle_error("write efd failed");}printf("child completed write loop\n");exit(0);default:sleep (2);printf("parent about to read\n");s = read(efd, &u, sizeof(uint64_t));if ( s != sizeof(uint64_t) ) {if (errno = EAGAIN) {printf("Parent read value %d\n", s);return 1;}handle_error("parent read failed");}printf("parent read %d , %llu (0x%llx) from efd\n",s, (unsigned long long)u, (unsigned long long) u);exit(0);case -1:handle_error("fork ");}return 0;}
 
以上所述是小編給大家介紹的Linux 新的API signalfd、timerfd、eventfd使用說明,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!