eventfd用法举例
时间: 2023-08-04 20:07:06 浏览: 55
eventfd是Linux提供的一种事件触发机制,可以在进程之间传递信号,也可以在同一进程的不同线程之间传递信号。下面是一个简单的eventfd用法举例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/eventfd.h>
int main()
{
int efd = eventfd(0, 0); // 创建一个eventfd对象
if (efd == -1) {
perror("eventfd");
exit(EXIT_FAILURE);
}
uint64_t value = 1;
ssize_t s = write(efd, &value, sizeof(uint64_t)); // 向eventfd对象写入数据
if (s != sizeof(uint64_t)) {
perror("write");
exit(EXIT_FAILURE);
}
uint64_t buf;
s = read(efd, &buf, sizeof(uint64_t)); // 从eventfd对象读取数据
if (s != sizeof(uint64_t)) {
perror("read");
exit(EXIT_FAILURE);
}
printf("value = %llu\n", buf);
close(efd); // 关闭eventfd对象
exit(EXIT_SUCCESS);
}
```
该程序首先创建一个eventfd对象,然后向对象写入一个64位的整数1,接着从对象中读取数据,最后关闭对象。由于每次读写操作都会增加eventfd对象中的计数器,因此程序运行后会输出“value = 1”。