Linux下使用eventfd实现进程间信号量操作

2024-02-02 21:38

本文主要是介绍Linux下使用eventfd实现进程间信号量操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1 前言

起源来自于单线程epoll_wait内部处理queue的思考,后来发现了linux支持一种自定义事件的fd,查找资料之余又发现了eventfd还有多进程信号灯的用处。。。本文翻译了eventfd的用法,并在文末附带demo进行实践。

2 介绍

eventfd 是 Linux 的一个系统调用,创建一个文件描述符用于事件通知,可在用户态编程使用。事件通知是基于计数器来实现,通过read、write实现计数器的加减。

2.1 eventfd

#include <sys/eventfd.h>
int eventfd(unsigned int initval, int flags);

该接口创建文件描述符fd,并按照initval初始化计数器。flags选项如下:

EFD_CLOEXEC (since Linux 2.6.27)Set the close-on-exec (FD_CLOEXEC) flag on the new file descriptor.   See  thedescription  of the O_CLOEXEC flag in open(2) for reasons why this may be use-ful.

open接口的O_CLOEXEC选项一样,表示在fork调用后,子进程继承所有父进程打开的文件描述符,这个选项再多进程中比较有用。

EFD_NONBLOCK (since Linux 2.6.27)Set the O_NONBLOCK file status flag on the new open file  description.   Usingthis flag saves extra calls to fcntl(2) to achieve the same result.

非阻塞选项,将影响read/write的调用结果。

EFD_SEMAPHORE (since Linux 2.6.30)Provide  semaphore-like semantics for reads from the new file descriptor.  Seebelow.

信号量选项,将影响read/write对计数器操作,详见2.2小节:

2.2 read

Each  successful  read(2) returns an 8-byte integer.
A read(2) will fail with the error EINVAL if the size of the supplied buffer is less than 8 bytes.

接口使用要求按8字节进行输入(u64的大小),否则抛EINVAL错误。

The value returned by read(2) is in host byte order-that is, 
the  native  byte order for integers on the host machine.

类似与网络操作,u64的输入是按照主机序进行,注意大小端问题。
另外,跟2.1小节选项相关的:

If EFD_SEMAPHORE was not specified and the eventfd counter has a nonzero value, 
then a read(2) returns  8  bytes  containing  that  value,  
and  the counter's value is reset to zero. 

如果没有设置EFD_SEMAPHORE,read接口表示从eventfd计数器读取8字节数据,数据值为计数器现有的值,读取完成后计数器将被重置成0。

If EFD_SEMAPHORE was specified and the eventfd counter has a nonzero value,
then a read(2) returns 8 bytes containing the value 1, 
and  the  counter's value is decremented by 1.

如果设置EFD_SEMAPHORE,read接口表示从eventfd计数器读取8字节数据,数据值一,读取完成后计数器减一操作。

If the eventfd counter is zero at the time of the call to read(2), 
then the all either blocks until the counter becomes nonzero (at  which  time,  
the read(2) proceeds as described above) or fails with the error EAGAIN if the file descriptor has been made nonblocking.

当计数器为0的时候,如果设置了阻塞选项,read调用将一直阻塞直到计数器变为非0状态,如果是非阻塞选项下,将会返回失败并抛errno=EAGAIN。

2.3 write

A write(2) call adds the 8-byte integer value supplied in its buffer to  the counter.
The maximum value that may be stored in the counter is the larges 
unsigned 64-bit value minus 1 (i.e.,  0xfffffffffffffffe).

write表示添加8字节的数值到计数器中,最大为MAX_U64 - 1。

If the addition would  cause  the  counter's  value  to  exceed the maximum, 
then the write(2) either blocks until a read(2) is performed on the file  descriptor,  
or fails with the error EAGAIN if the file descriptor has been made nonblocking.

如果超出上限,阻塞选项下将一直阻塞直到计数器的值被read走为止,非阻塞选项下将会返回失败并抛errno=EAGAIN。

3. 实践

3.1 样例


#include <assert.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/eventfd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "common.h"#define WORKER_NUM 4
#define HAVE_SEMAPHORE 1int main(int argc, char *argv[])
{pid_t pid[WORKER_NUM] = {0};int res = -1;
#if HAVE_SEMAPHOREint fd = eventfd(0, EFD_SEMAPHORE | EFD_CLOEXEC | EFD_NONBLOCK);
#elseint fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
#endifassert(fd);for (int ix = 0; ix < WORKER_NUM; ix++) {pid[ix] = fork();if (pid[ix] < 0) {assert(0);}else if (pid[ix] > 0) {continue;}test_worker(fd);goto out;}test_master(fd);for (int ix = 0; ix < WORKER_NUM; ix++) {wait(NULL);}
out:close(fd);exit(EXIT_SUCCESS);
}

主函数中,将eventfd创建处理,并创建4个worker对应1个master,master一会用于增加计数器,worker进行计数器取值。注意使用了 HAVE_SEMAPHORE 控制,到时在第3.2小节说明现象的区别。

void test_master(int fd)
{
#if HAVE_SEMAPHOREu64 val = 1;
#elseu64 val = 1000;
#endifu64 sum = 0;for (int ix = 0; ix < 10; ix++) {assert(write(fd, &val, sizeof(val)) > 0);sum += val;printf("%x Send: %llu / %llu\n", (u32)getpid(), val, sum);usleep(100 * 1000);}
}

master中对计数器进行加操作,开启信号量模式 HAVE_SEMAPHORE 时为加一动作,否则加一堆。
注意eventfd只能使用 write进行操作,不能使用send接口。。
为了方便观察现象,master每次加计数器后进行短时休眠。

void test_worker(int fd)
{u64 sum = 0;int res = -1;for (int ix = 0; ix < 20; ix++) {u64 val = 0;res = read(fd, &val, sizeof(val));if (res < 0) {if (errno == EAGAIN) {usleep(100 * 1000);continue;}assert(0);}sum += val;printf("%x Recv: %llu / %llu\n", (u32)getpid(), val, sum);}printf("%x Recv sum: %llu quit...\n", (u32)getpid(), sum);
}

worker这块读取数值,并进行统计打印,由于使用了非阻塞选项,所以额外判断了eagain动作。为了方便阐述效果,使用睡眠+循环控制worker的超时退出动作。

3.2 结果分析

开启信号量模式,发现多个worker是轮流对计数器减一操作,存在相互竞争的关系,最终总数数值正确。同时试验了其他方式,worker也可以进行计数器加一操作,最终实现的是信号灯的效果。

1e92 Send: 1 / 1
1e94 Recv: 1 / 1
1e92 Send: 1 / 2
1e92 Send: 1 / 3
1e95 Recv: 1 / 1
1e95 Recv: 1 / 2
1e92 Send: 1 / 4
1e96 Recv: 1 / 1
1e92 Send: 1 / 5
1e92 Send: 1 / 6
1e93 Recv: 1 / 1
1e93 Recv: 1 / 2
1e92 Send: 1 / 7
1e93 Recv: 1 / 3
1e96 Recv: 1 / 2
1e92 Send: 1 / 8
1e92 Send: 1 / 9
1e94 Recv: 1 / 2
1e92 Send: 1 / 10
1e96 Recv: 1 / 3
1e93 Recv sum: 3 quit...
1e96 Recv sum: 3 quit...
1e95 Recv sum: 2 quit...
1e94 Recv sum: 2 quit...

没开启 EFD_SEMAPHORE,多个worker进程也存在相互竞争关系,由于master进行休眠控制,现象是1000、1000地读写。关闭休眠的时候,work的一次读取是会出现>1000动作的。

1ea5 Recv: 1000 / 1000
1e9d Send: 1000 / 1000
1e9d Send: 1000 / 2000
1ea6 Recv: 1000 / 1000
1e9d Send: 1000 / 3000
1ea6 Recv: 1000 / 2000
1e9d Send: 1000 / 4000
1ea4 Recv: 1000 / 1000
1e9d Send: 1000 / 5000
1ea6 Recv: 1000 / 3000
1ea6 Recv: 1000 / 4000
1e9d Send: 1000 / 6000
1e9d Send: 1000 / 7000
1ea4 Recv: 1000 / 2000
1e9d Send: 1000 / 8000
1ea4 Recv: 1000 / 3000
1e9d Send: 1000 / 9000
1ea3 Recv: 1000 / 1000
1e9d Send: 1000 / 10000
1ea3 Recv: 1000 / 2000
1ea6 Recv sum: 4000 quit...
1ea4 Recv sum: 3000 quit...
1ea3 Recv sum: 2000 quit...
1ea5 Recv sum: 1000 quit...

4. 结论

总体来讲,eventfd 功能是挺方便的,完美地将自定义事件与文件描述符结合起来。
内部的工作原理还缺少一下深入学习的地方。本文只列举了多进程的使用,而实际eventfd主要是用来跟epoll配合的,后续还需要再实践一下。

这篇关于Linux下使用eventfd实现进程间信号量操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/672048

相关文章

Linux线程之线程的创建、属性、回收、退出、取消方式

《Linux线程之线程的创建、属性、回收、退出、取消方式》文章总结了线程管理核心知识:线程号唯一、创建方式、属性设置(如分离状态与栈大小)、回收机制(join/detach)、退出方法(返回/pthr... 目录1. 线程号2. 线程的创建3. 线程属性4. 线程的回收5. 线程的退出6. 线程的取消7.

Linux下进程的CPU配置与线程绑定过程

《Linux下进程的CPU配置与线程绑定过程》本文介绍Linux系统中基于进程和线程的CPU配置方法,通过taskset命令和pthread库调整亲和力,将进程/线程绑定到特定CPU核心以优化资源分配... 目录1 基于进程的CPU配置1.1 对CPU亲和力的配置1.2 绑定进程到指定CPU核上运行2 基于

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

golang程序打包成脚本部署到Linux系统方式

《golang程序打包成脚本部署到Linux系统方式》Golang程序通过本地编译(设置GOOS为linux生成无后缀二进制文件),上传至Linux服务器后赋权执行,使用nohup命令实现后台运行,完... 目录本地编译golang程序上传Golang二进制文件到linux服务器总结本地编译Golang程序

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

Linux下删除乱码文件和目录的实现方式

《Linux下删除乱码文件和目录的实现方式》:本文主要介绍Linux下删除乱码文件和目录的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux下删除乱码文件和目录方法1方法2总结Linux下删除乱码文件和目录方法1使用ls -i命令找到文件或目录

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控