好久沒更新了,今天看一下第三種新的fd:eventfd類似于管道的概念,可以實現線程間的事件通知,所不同的是eventfd的緩沖區大小是sizeof(uint64_t)也就是8字節,它是一個64位的計數器,寫入遞增計數器,讀取將得到計數器的值,并且清零。看一下代碼:
[cpp] view plaincopy
#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[])??{?????uint64_t?u;???????????int?efd?=?eventfd(10,?0);?????if?(efd?==?-1)?????????handle_error("eventfd");??????????int?ret?=?fork();?????if(ret?==?0)?????{?????????for?(int?j?=?1;?j?<?argc;?j++)?{?????????????printf("Child?writing?%s?to?efd\n",?argv[j]);?????????????u?=?atoll(argv[j]);?????????????ssize_t?s?=?write(efd,?&u,?sizeof(uint64_t));?????????????if?(s?!=?sizeof(uint64_t))?????????????????handle_error("write");?????????}?????????printf("Child?completed?write?loop\n");???????????exit(EXIT_SUCCESS);?????}?????else?????{?????????sleep(2);???????????ssize_t?s?=?read(efd,?&u,?sizeof(uint64_t));?????????if?(s?!=?sizeof(uint64_t))?????????????handle_error("read");?????????printf("Parent?read?%llu?from?efd\n",(unsigned?long?long)u);?????????exit(EXIT_SUCCESS);?????}??}??
比較簡單,不做過解釋。子進程寫入命令行中傳入的參數,父進程讀取其中計數器的值。
運行結果:
[cpp] view plaincopy
./eventfd?10?20?30??Child?writing?10?to?efd??Child?writing?20?to?efd??Child?writing?30?to?efd??Child?completed?write?loop??Parent?read?70?from?efd??
命令行傳入的是10、20、30其和應為60,為啥讀取的是70呢?請看15行調用eventfd時第一個參數是10,這個參數是創建eventfd時初始化計數器的值。
總結
以上是生活随笔為你收集整理的linux新的API signalfd、timerfd、eventfd使用说明——eventfd的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。