gpt4 book ai didi

linux - Linux 中 'n' 进程之间的文件访问(读/写)同步

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:16:05 26 4
gpt4 key购买 nike

我这学期正在学习操作系统,只是想知道 Linux 如何处理文件访问(读/写)同步,它使用信号量、互斥量或监视器的默认实现是什么?你能告诉我在源代码或我自己的 Ubuntu 副本中可以找到它的位置以及如何禁用它吗?

我需要禁用它,这样我才能检查我自己的实现是否有效,以及如何将我自己的实现添加到系统中。

这是我目前的计划,请告诉我是否可以:

  1. 禁用默认实现,添加我自己的。 (如果需要重新编译内核)
  2. 我自己的版本会跟踪每个传入进程并维护他们正在使用的文件列表,每当文件重复时我会检查它是读取进程还是写入进程
  3. 我将采用读者偏好的解决方案来解决读者和作者的问题。

最佳答案

内核不强加进程同步(它应该由进程执行,而内核只提供工具),但它可以保证某些操作的原子性:原子操作不能被中断并且它的结果不能被并行运行的其他操作改变。

说到写入文件,它有一些原子性保证。来自 man -s3 write :

Atomic/non-atomic: A write is atomic if the whole amount written in one operation is not interleaved with data from any other process. This is useful when there are multiple writers sending data to a single reader. Applications need to know how large a write request can be expected to be performed atomically. This maximum is called {PIPE_BUF}. This volume of IEEE Std 1003.1-2001 does not say whether write requests for more than {PIPE_BUF} bytes are atomic, but requires that writes of {PIPE_BUF} or fewer bytes shall be atomic.

关于 SO 的一些讨论:Atomicity of write(2) to a local filesystem .

为了保持原子性,各种内核例程持有 inode 的 i_mutex 互斥量。 IE。在 generic_file_write_iter() :

mutex_lock(&inode->i_mutex);
ret = __generic_file_write_iter(iocb, from);
mutex_unlock(&inode->i_mutex);

因此其他 write() 调用不会干扰您的调用。但是,读者不会锁定 i_mutex,因此他们可能会得到无效数据。读者的实际锁定在 page cache 中执行,所以一页(x86 上为 4096 字节)是保证内核原子性的最小数据量。

说到重新编译内核来测试您自己的实现,有两种方法:从 http://kernel.org/ 下载 vanilla 内核(或从 Git),修补和构建它——这很容易。重新编译 Ubuntu 内核更难——它需要使用 Debian 构建工具:https://help.ubuntu.com/community/Kernel/Compile

我不清楚您要通过自己的实现实现什么目标。如果你想应用更严格的同步规则,也许是时候看看 TxOS

关于linux - Linux 中 'n' 进程之间的文件访问(读/写)同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29867236/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com