如果 2 个不同的进程同时在同一个文件上调用 write 系统调用会发生什么 [英] What happens if a write system call is called on same file by 2 different processes simultaneously

查看:13
本文介绍了如果 2 个不同的进程同时在同一个文件上调用 write 系统调用会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

操作系统是否正确处理它?<​​/p>

或者我必须调用flock()吗?

解决方案

虽然操作系统不会崩溃,文件系统也不会损坏,但调用 write()保证是原子的,除非所讨论的文件描述符是一个管道,并且要写入的数据量是 PIPE_MAX 字节或更少.标准的相关部分:

<块引用>

尝试写入管道或 FIFO 有几个主要特征:

  • 原子/非原子:如果在一个操作中写入的全部量没有与来自任何其他进程的数据交错,则写入是原子的.当有多个写入器向单个读取器发送数据时,这很有用.应用程序需要知道可以以原子方式执行的写入请求有多大.此最大值称为 {PIPE_BUF}.本卷 IEEE Std 1003.1-2001 并未说明超过 {PIPE_BUF} 字节的写入请求是否是原子的,但要求 {PIPE_BUF} 或更少字节的写入应该是原子的.

[...]

因此,原则上,您必须同时锁定写入者,否则您写入的数据可能会混淆和乱序(即使在同一写入中),或者您可能有多个写入相互覆盖.但是,有一个例外 - 如果您通过 O_APPEND,您的写入将是有效的原子:

<块引用>

如果设置了文件状态标志的 O_APPEND 标志,则文件偏移量应在每次写入之前设置为文件末尾,并且在更改文件偏移量和写入操作之间不应发生中间文件修改操作.

虽然这对于非O_APPEND 写入或同时读取而言不一定是原子的,但如果所有写入者都使用O_APPEND,并且您在执行之前以某种方式同步>阅读,你应该没事的.

Does the OS handle it correctly?

Or will I have to call flock()?

解决方案

Although the OS won't crash, and the filesystem won't be corrupted, calls to write() are NOT guarenteed to be atomic, unless the file descriptor in question is a pipe, and the amount of data to be written is PIPE_MAX bytes or less. The relevant part of the standard:

An attempt to write to a pipe or FIFO has several major characteristics:

  • 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.

[...]

As such, in principle, you must lock with simultaneous writers, or your written data may get mixed up and out of order (even within the same write) or you may have multiple writes overwriting each other. However, there is an exception - if you pass O_APPEND, your writes will be effectively atomic:

If the O_APPEND flag of the file status flags is set, the file offset shall be set to the end of the file prior to each write and no intervening file modification operation shall occur between changing the file offset and the write operation.

Although this is not necessarily atomic with respect to non-O_APPEND writes, or simultaneous reads, if all writers use O_APPEND, and you synchronize somehow before doing a read, you should be okay.

这篇关于如果 2 个不同的进程同时在同一个文件上调用 write 系统调用会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆