好久沒更新了,今天看一下第三種新的fd:eventfd類似于管道的概念,可以實現(xiàn)線程間的事件通知,所不同的是eventfd的緩沖區(qū)大小是sizeof(uint64_t)也就是8字節(jié),它是一個64位的計數(shù)器,寫入遞增計數(shù)器,讀取將得到計數(shù)器的值,并且清零。看一下代碼:
[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);?????}??}??
比較簡單,不做過解釋。子進(jìn)程寫入命令行中傳入的參數(shù),父進(jìn)程讀取其中計數(shù)器的值。
運(yùn)行結(jié)果:
[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其和應(yīng)為60,為啥讀取的是70呢?請看15行調(diào)用eventfd時第一個參數(shù)是10,這個參數(shù)是創(chuàng)建eventfd時初始化計數(shù)器的值。
總結(jié)
以上是生活随笔為你收集整理的linux新的API signalfd、timerfd、eventfd使用说明——eventfd的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。