标签:
参考:http://www.man7.org/linux/man-pages/man2/eventfd.2.html
简单来说,这个函数就是创建一个用于事件通知的文件描述符。它类似于pipe,但是不像pipe一样需要两个描述符,它只需要一个描述就可以实现进程间通信了。
详细的介绍请看参考资料。
示例:
#include <sys/eventfd.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) int main(int argc, char **argv) { int efd, j; uint64_t u; ssize_t s; if (argc < 2) { fprintf(stderr, "Usage: %s <num>...\n", argv[0]); exit(EXIT_FAILURE); } efd = eventfd(0, 0); if (efd == -1) { handle_error("eventfd"); } 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); s = write(efd, &u, sizeof(uint64_t)); if (s != sizeof(uint64_t)) { handle_error("write"); } } printf("Child completed write loop\n"); exit(EXIT_SUCCESS); case -1: handle_error("fork"); default: sleep(2); printf("Parent about to read\n"); s = read(efd, &u, sizeof(uint64_t)); if (s != sizeof(uint64_t)) { handle_error("read"); } printf("Parent read %llu (0x%llx) from efd\n", (unsigned long long)u, (unsigned long long)u); exit(EXIT_SUCCESS); } }
执行结果:
为什么写入这个文件描述符的数字,读取到的居然是它们的和?
明白了,仔细看了一下在该文件描述符上的read、write操作,就理解了,read从该文件描述符读取一个uini64_t类型的整数,write则是把要写入的数字加到已有的整数上。
标签:
原文地址:http://www.cnblogs.com/lit10050528/p/4758284.html