這個系統調用可以創建一個類似管道的東西,但比管道更簡單,它的讀和寫緩衝區只有8個字節,它會通過eventfd創建一個描述符fd,用於線程或進程間通信。簡單來說,就是進程A被write一個n,那麼進程B可以通過read讀到這個n,當然在使用過程中,n是A和B之間協商的一個有意義的數字。看一下網上的代碼就明白了
- #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;
- int j;
- if ( argc < 2 ) {
- fprintf(stderr, "input <num> 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下網絡編程的時候,可以用此fd去做線程間的通信或者喚醒事件分離器(select poll epoll_wait),類似iocp的PostQueuedCompletionStatus,但請注意,此函數在2.6.22內核版本以後有效。