How can I tell if a file is open elsewhere in C on

2020-02-10 06:31发布

问题:

How can I tell if a file is open in 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.

Thanks, Chenz

回答1:

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:

  • 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. You look for the presence of *.finished when processing files.
  • 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.


回答2:

I don't think there is any way to do this in pure C (it wouldn't be cross platform).

If you know what files you are using ahead of time, you can use inotify to be notified when they open.



回答3:

C has facilities for handling files, but not much for getting information on them. 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.



回答4:

generally you can't do that for variuos reasons (e.g. you cannot say if the file is opened with another user).

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)



回答5:

Use the lsof command. (List Open Files).



回答6:

If you are in control of both producer and consumer, you could use lockf() of flock() to lock the file.



回答7:

there is lsof command on most distros, which shows all currently open files, you can ofcourse grep its output if your files are in the same directory or have some recognizable name pattern.



标签: c linux file-io