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

2020-02-10 06:27发布

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

标签: c linux file-io
7条回答
迷人小祖宗
2楼-- · 2020-02-10 06:54

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.
查看更多
太酷不给撩
3楼-- · 2020-02-10 06:54

Use the lsof command. (List Open Files).

查看更多
你好瞎i
4楼-- · 2020-02-10 06:56

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.

查看更多
叛逆
5楼-- · 2020-02-10 07:04

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

查看更多
干净又极端
6楼-- · 2020-02-10 07:06

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.

查看更多
7楼-- · 2020-02-10 07:11

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.

查看更多
登录 后发表回答