小编Vin*_*lai的帖子

Linux 中进程之间的 write(2)/read(2) 原子性

我有一个案例,有两个进程作用于同一个文件 - 一个作为写入器,一个作为读取器。该文件是一行文本文件,编写器在循环中重写该行。读者阅读该行。伪代码如下所示:

写入程序

char buf[][18] = {
"xxxxxxxxxxxxxxxx",
"yyyyyyyyyyyyyyyy"
};
i = 0;
while (1) {
 pwrite(fd, buf[i], 18, 0);
 i = (i + 1) % 2;
}
Run Code Online (Sandbox Code Playgroud)

读者进程

while(1) {
  pread(fd, readbuf, 18, 0);
  //check if readbuf is either buf[0] or buf[1]
}
Run Code Online (Sandbox Code Playgroud)

运行这两个进程一段时间后,我可以看到readbufxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyxx

我的理解是对于最大 512 字节的写入将是原子的。但从我的实验来看,原子性似乎只针对 16 个字节。

手册页没有提及任何关于普通文件的原子性,它只提到了 512 字节的管道原子性。

我已经用 tmpfs 和 ext4 尝试过,结果是相同的。使用O_SYNCext4 写入变得原子,我理解它,因为写入在到达磁盘之前不会返回,但O_SYNC对 tmpfs ( ) 没有帮助/dev/shm

linux filesystems tmpfs

6
推荐指数
1
解决办法
2625
查看次数

标签 统计

filesystems ×1

linux ×1

tmpfs ×1