简体   繁体   English

如何判断文件是否在Linux上的其他位置打开?

[英]How can I tell if a file is open elsewhere in C on Linux?

How can I tell if a file is open in C? 如何判断文件是否在C中打开? I think the more technical question would be how can I retrieve the number of references to a existing file and determine with that info if it is safe to open. 我认为更技术性的问题是如何检索对现有文件的引用数量,并确定是否可以安全打开该信息。

The idea I am implementing is a file queue. 我正在实现的想法是文件队列。 You dump some files, my code processes the files. 你转储一些文件,我的代码处理文件。 I don't want to start processing until the producer closes the file descriptor. 在生产者关闭文件描述符之前,我不想开始处理。

Everything is being done in linux. 一切都在linux中完成。

Thanks, Chenz 谢谢,陈兹

Digging out that info is a lot of work(you'd have to search thorugh /proc/*/fd You'd be better off with any of: 挖掘这些信息是很多工作(你必须搜索thorugh / proc / * / fd你最好用以下任何一个:

  • Save to temp then rename. 保存到临时然后重命名。 Either write your files to a temporary filename or directory, when you're done writinh, rename it into the directory where your app reads them. 将文件写入临时文件名或目录,当您完成写入后,将其重命名为应用程序读取它们的目录。 Renaming is atomic, so when the file is present you know it's safe to read. 重命名是原子的,所以当文件存在时你知道它是安全的。
  • Maybe a variant of the above , when you're done writing the file foo you create an empty file named foo.finished . 也许是上面的变体,当你完成foo文件的编写时,你会创建一个名为foo.finished的空文件。 You look for the presence of *.finished when processing files. 在处理文件时,您会查找* .finished的存在。
  • Lock the files while writing, that way reading the file will just block until the writer unlocks it. 在写入时锁定文件,这样读取文件就会阻塞,直到作者解锁它。 See the flock/lockf functions, they're advisory locks though so both the reader and writer have to lock , and honor the locks. 看到flock / lockf函数,它们是咨询锁,所以读者和作者都必须锁定并尊重锁。

I don't think there is any way to do this in pure C (it wouldn't be cross platform). 我不认为在纯C中有任何方法可以做到这一点(它不会是跨平台的)。

If you know what files you are using ahead of time, you can use inotify to be notified when they open. 如果您提前知道正在使用哪些文件,则可以使用inotify在打开时收到通知。

C has facilities for handling files, but not much for getting information on them. C具有处理文件的功能,但对于获取有关它们的信息并不多。 In portable C, about the only thing you can do is try to open the file in the desired way and see if it works. 在便携式C中,您唯一能做的就是尝试以所需的方式打开文件,看看它是否有效。

generally you can't do that for variuos reasons (eg you cannot say if the file is opened with another user). 通常你不能出于variuos的原因(例如,你不能说文件是否与其他用户一起打开)。

If you can control the processes that open the file and you are try to avoid collisions by locking the file (there are many libraries on linux in order do that) 如果你可以控制打开文件的进程,你试图通过锁定文件来避免冲突(linux上有很多库就可以了)

Use the lsof command. 使用lsof命令。 (List Open Files). (列出打开的文件)。

如果你同时控制生产者和消费者,你可以使用flock()的lockf()来锁定文件。

在大多数发行版上都有lsof命令,它显示了所有当前打开的文件,如果你的文件在同一个目录中或者有一些可识别的名称模式,你可以使用grep它的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM