这个系统调用可以创建一个类似管道的东西,但比管道更简单,它的读和写缓冲区只有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内核版本以后有效。
转载于:https://blog.51cto.com/chenchao40322/738721