您的位置:首页 > 运维架构 > Linux

linux之eventfd()

2015-08-25 18:23 507 查看
参考: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则是把要写入的数字加到已有的整数上。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: