tags:

views:

756

answers:

8

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

A: 

Open a shell and type

man ftrylockfile

You open the file, then pass it to this function and if the return value is nonzero the file is already locked, otherwise it will lock the file and return 0.

then when you are finished you funclockfile() it.

klez
This will not work, he needs to find out whether *another* program has a file open.
zvrba
+1  A: 

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.

Zifre
Yes, he can also use inotify to detect that a file has been closed.
zvrba
+4  A: 

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.
nos
I've come to the conclusion that the second suggestion is the best for my situation. Thanks!
Crazy Chenz
A: 

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.

David Thornley
A: 

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)

dfa
A: 

Use the lsof command. (List Open Files).

kmarsh
A: 

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

zvrba
A: 

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.

justadreamer