Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

linux

file-io

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

like image 485
Crazy Chenz Avatar asked Jul 06 '09 14:07

Crazy Chenz


2 Answers

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.
like image 165
nos Avatar answered Nov 14 '22 22:11

nos


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.

like image 32
Zifre Avatar answered Nov 14 '22 22:11

Zifre