gpt4 book ai didi

c++ - _sopen_s 如何管理对同一文件的多次写入

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

我有一个 C++ 应用程序可以处理多个连接并写入文件。当使用带有参数 _SH_DENYNO 的函数 _sopen_s 时,所有同时工作的线程都在写入文件,我没有看到数据丢失。您能告诉我该函数如何管理对文件的访问,以免数据丢失吗?

亲切的问候

最佳答案

如果您使用 write() ,或者它的一些操作系统提供的变体,个人 write()调用往往是这样实现的,即每次调用 write()是原子的,因为这 POSIX statement regarding write() 的含义:

On a regular file or other file capable of seeking, the actual writing of data shall proceed from the position in the file indicated by the file offset associated with fildes. Before successful return from write(), the file offset shall be incremented by the number of bytes actually written. On a regular file, if this incremented file offset is greater than the length of the file, the length of the file shall be set to this file offset.

这有点难以以允许来自单独 write() 的交错数据的方式实现调用相同的文件描述符,因为如果数据交错,则完成后文件偏移量的变化将不等于“实际写入的字节数”。因此,该声明可以解释为对 write() 的原子性的隐含要求。调用任何“常规文件或其他能够搜索的文件”。

此外,还有明确的 POSIX requirementwrite()调用小于或等于 PIPE_BUF 的管道字节是原子的:

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 POSIX.1-2008 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.

write()刚得到一个 int对于没有其他直接可用的文件描述符信息的文件描述符,最简单的实现方式 write()以一种满足原子 write() 的 POSIX 要求的方式到管道是使每个write()调用原子。

因此,虽然没有要求 原子性,除非您写的小于或等于 PIPE_BUF实际管道的字节,write()倾向于以原子方式实现所有内容。

现在,这并不意味着无论文件描述符指向什么,都不会分解数据或将其与其他数据交错。例如,如果两个线程各自尝试调用一个 write(),我不会对看到交错数据感到惊讶。将几 GB 的数据从 MPEG 文件同时传输到同一个 TCP 套接字的操作。

而且您实际上并没有调用 write() .但底层实现可能是共享的。

关于c++ - _sopen_s 如何管理对同一文件的多次写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33276159/

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