我如何知道我是唯一打开文件句柄的人?

发布于 2024-08-18 21:15:33 字数 313 浏览 2 评论 0原文

我遇到一种情况,我需要从目录中获取文件并在它们出现时尽快对其进行处理。将文件送入此目录的过程正在以相当快的速度写入它们(高峰时段可达每分钟一千个),我需要将它们拉出并在它们到达时对其进行处理。

我遇到的一个问题是我知道我的 C++ 代码已经打开了发送服务器已完成的文件——也就是说,本地 FTP 服务器尚未写入数据。

在 Solaris 下,如何打开一个文件并 100% 确定没有其他人打开该文件?

我应该注意,一旦文件被写入并关闭它,其他服务器将不会再次打开它,所以如果我可以打开它并且知道我拥有独占访问权限,我就不需要担心检查我是否我仍然是唯一拥有该文件的人。

I have a situation where I need to pick up files from a directory and process them as quickly as they appear. The process feeding files into this directory is writing them at a pretty rapid rate (up to a thousand a minute at peak times) and I need to pull them out and process them as they arrive.

One problem I've had is knowing that my C++ code has opened a file that the sending server has finished with -- that is, that the local FTP server isn't still writing to.

Under Solaris, how can I open a file and know with 100% certainty that no-one else has it open?

I should note that once the file has been written to and closed off it the other server won't open it again, so if I can open it and know I've got exclusive access I don't need to worry about checking that I'm still the only one with the file.

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

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

发布评论

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

评论(2

尝蛊 2024-08-25 21:15:33

您可以将flock()与操作LOCK_EX一起使用以确保独占访问。 fcntl() 是另一种可能的方法

#include <sys/file.h>

int flock(int fd, int operation);   

编辑:有两种方法可以做到这一点,找到一个在接收过程中锁定文件的 ftp 服务器。
如果您使用 pfiles 或 lsof 监控 ftp 服务器进程,恐怕您不会 100% 安全(可在此处获取 http://www.sunfreeware.com/),以确保没有其他人正在访问这些文件。

也许您可以检查传入文件的时间戳,如果它们在几分钟内没有更改,则可以安全地获取、处理或对它们执行某些操作。

You can used flock() with operation LOCK_EX to ensure exclusive access. fcntl() is another possible way

#include <sys/file.h>

int flock(int fd, int operation);   

EDIT: Two ways to do this, find an ftp server which locks the file during receiving.
I'm afraid you will not be 100% safe if you monitor the ftp server process, using pfiles or lsof (which is available here http://www.sunfreeware.com/) to make sure that no one else is accessing the files.

Maybe you can check the timestamps of the incomming files and if they havn't changed for a few minutes it would be safe to fetch,process or do something with them.

看透却不说透 2024-08-25 21:15:33

将文件送入目录的进程是否属于您?如果是这种情况,请将文件的扩展名重命名为 .working,这样您就不会拾取正在使用的文件。

编辑:既然你说它是solaris,请编写一个shell脚本并使用pfiles命令检查该进程是否仍在使用你想要使用的文件。如果没有开始处理文件。

Is the process that feeds files into the directory is owned by you? If that is the case, then rename the file's extension to .working so that you don't pick up the file that is being used.

EDIT: Since you said it is solaris, write a shell script and use pfiles command to check if the process still uses the file you want to use. If not start processing the file.

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