如何确保当我的进程对文件进行操作时,没有其他进程尝试写入或删除它?

发布于 2024-09-26 07:54:36 字数 136 浏览 2 评论 0原文

如果我的进程尝试从文件中读取数据,那么如何从我的代码(C 语言)中确保没有其他进程写入或删除它(包括用于删除文件的系统命令)?

另外,这可以在所有操作系统(Windows、Linux、Solaris、HP-UX、VxWorks 等)上实现吗?

If my process is trying to read from a file, then how do I ensure from my code (C Language) that no other process either writes to it or deletes it (include system commands for deleting the file)?

Also, can this be achieved on all OS (Windows, Linux, Solaris, HP-UX, VxWorks etc)?

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

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

发布评论

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

评论(4

£噩梦荏苒 2024-10-03 07:54:37

复制该文件,进行更改,然后将其重命名为原始文件。

另一种方法(如果该文件尚不存在)是使用独占标志创建该文件,然后将其从文件系统中删除。执行写入,然后将其硬链接回文件系统(它目前仅作为打开的 inode 存在)。您可以使用 /proc 作为源路径。

Copy the file, make your changes, then rename it back over the original.

Another method, if the file doesn't yet exist, is to create the file using exclusive flags, then delete it from the filesystem. Perform your writing, then hard link it back into the filesystem (it presently exists only as an open inode). You can make use of /proc for the source path.

如梦初醒的夏天 2024-10-03 07:54:36

编辑:我会回答 Unix/Linux

正如 gspr 和其他人所说,请查看使用 fcntlflock 等的文件锁定。但是,请注意,这些是ADVISORY LOCKING方法。

这意味着什么?这意味着您可以警告其他进程您当前正在访问文件或文件的一部分,但您无法强制阻止它们忽略您并在您的文件上进行写入

没有强制锁定原语。您可以利用权限来发挥自己的优势,但您永远无法得到完全的保证——root 用户始终可以超越您的限制。我认为没有办法解决这个问题。

Edit: I'll answer for Unix/Linux

As gspr and others said, take a look at file locking using fcntl, flock, etc. However, be warned that those are ADVISORY LOCKING methods.

What does this mean? It means you can warn other processes that you are currently accesing a file, or a portion of it, but you can't forcibly keep them from ignoring you and writing all over your file.

There are no COMPULSORY locking primitives. You can use permissions to your advantage, but you'll never have full guarantees -- the root user can always override your limitations. I don't think there's a way to work around that.

小瓶盖 2024-10-03 07:54:36

对于 POSIX 系统,请查看 fcntlflock 也可能令人感兴趣,尽管我不认为它是 POSIX 的一部分。

For POSIX systems, take a look at fcntl. flock could also be of interest, although I don't think it's a part of POSIX.

银河中√捞星星 2024-10-03 07:54:36

您必须使用读取共享权限打开该文件,这意味着尝试打开该文件的其他人只能获得读取访问权限。正如 @Pointy 所说,这是特定于操作系统的,您可能必须为 Windows、Linux 等单独编码。但是,大多数现代操作系统应该支持这一点。

You have to open the file with READ sharing permissions, which means anyone else trying to open it can only get read access. As @Pointy says, this is OS specific and you'll probably have to code this separately for Windows, Linux, etc. However, most modern OSs should support this.

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