多个进程上的文件

发布于 2024-07-17 02:48:34 字数 167 浏览 8 评论 0原文

如果我的一个进程打开一个文件,假设只进行读取,那么操作系统是否保证在我正在读取时没有其他进程会在该文件上写入内容? 让读取过程保留旧文件版本的第一部分和新文件版本的第二部分,从而使数据完整性受到质疑?

我不是在谈论没有搜索的管道,而是在常规文件上,具有搜索选项(至少在仅使用一个进程打开时)。

If one of my processes open a file, let's say for reading only, does the O.S guarantee that no other process will write on it as I'm reading, maybe
leaving the reading process with first part of the old file version, and second part of the newer file version, making data integrity questionable?

I am not talking about pipes which have no seek, but on regular files, with seek option (at least when opened with only one process).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情何以堪。 2024-07-24 02:48:34

不,其他进程可以在您读取文件时更改文件内容。 尝试运行“man fcntl”并忽略有关“咨询”锁的部分; 这些是“可选”锁,进程只需在需要时才需要注意。 相反,寻找(唉,非 POSIX)“强制”锁。 这些可以保护您免受其他程序的侵害。 尝试读锁。

No, other processes can change the file contents as you are reading it. Try running "man fcntl" and ignore the section on "advisory" locks; those are "optional" locks that processes only have to pay attention to if they want. Instead, look for the (alas, non-POSIX) "mandatory" locks. Those are the ones that will protect you from other programs. Try a read lock.

惯饮孤独 2024-07-24 02:48:34

不,如果您打开一个文件,其他进程就可以写入它,除非您使用锁。

在 Linux 上,您可以使用以下命令在文件上添加咨询锁:

#include <sys/file.h>

...

flock(file_descriptor,LOCK_EX); // apply an advisory exclusive lock

No, if you open a file, other processes can write to it, unless you use a lock.

On Linux, you can add an advisory lock on a file with:

#include <sys/file.h>

...

flock(file_descriptor,LOCK_EX); // apply an advisory exclusive lock
零度℉ 2024-07-24 02:48:34

任何可以打开该文件进行写入的进程都可以对其进行写入。 写入可能与您自己的写入同时发生,从而导致(可能)不确定状态。

作为应用程序编写者,您有责任确保不会发生不好的事情。 在我看来,强制锁定不是一个好主意。

更好的想法是不要向您不想写入文件的进程授予写访问权限。

如果多个进程打开一个文件,它们将拥有独立的文件指针,因此它们可以seek()而不会互相影响。

如果一个文件是由线程程序(或者更一般地与另一个共享其文件描述符的任务)打开的,则文件指针也是共享的,因此您需要使用另一种方法来访问文件以避免竞争条件导致混乱 -通常是 pread、pwrite 或分散/聚集函数 readv 和 writev。

Any process which can open the file for writing, may write to it. Writes can happen concurrently with your own writes, resulting in (potentially) indeterminate states.

It is your responsibility as an application writer to ensure that Bad Things don't happen. In my opinion mandatory locking is not a good idea.

A better idea is not to grant write access to processes which you don't want to write to the file.

If several processes open a file, they will have independent file pointers, so they can seek() and not affect one another.

If a file is opened by a threaded program (or a task which shares its file descriptors with another, more generally), the file pointer is also shared, so you need to use another method to access the file to avoid race conditions causing chaos - normally pread, pwrite, or the scatter/gather functions readv and writev.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文