1

As the title states:

  • My program opens a file.
  • Something comes along and moves that file. Inode should be the same, but name is different.
  • Close the file, then delete, but its not there anymore

So how can I detect that it has been moved and delete the correct filename?

Any ideas?

talnicolas
  • 13,885
  • 7
  • 36
  • 56
Jaime
  • 1,182
  • 2
  • 12
  • 29
  • Are you concerned about the cross-filesystem moves (copy-and-delete, inode not kept) and non-inode filesystems (e.g. FAT) ? – MSalters Jan 17 '12 at 10:06

3 Answers3

2

You could use inotify to detect a change to the old name (look for the IN_MOVE_SELF event). But if your real goal is simply to delete the file's name, you can just do that (using unlink(2)) immediately after opening the file. Unix file semantics will allow you to keep using the open file, and the data on disk will not actually be deleted until your handle is closed. And then no one will be able to rename the file.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • The problem with unlink is a race condition. If the file is moved before unlink takes place or can finish, no dice. – Jaime Jan 16 '12 at 19:50
  • Then move the file first, before you open it. Nobody will know about the new name, which you can then open and unlink at the end. If this still doesn't solve your problem, then you're going to have to describe in quite a bit more detail what you are actually trying to accomplish. – John Zwinck Jan 16 '12 at 19:52
0

try to access(2) the file before closing it. If you get ENOENT, the file has been moved. Follow the /proc/self/fd/$open_file_number/ symlink to find the new filename using readlink(2).

ggiroux
  • 6,544
  • 1
  • 22
  • 23
  • Seems like there is a race here too. If access indicates it hasn't been moved and I try to delete it, but something moves in between those calls, I'm out of luck – Jaime Jan 16 '12 at 19:51
  • Using `access` won’t handle the case where the name now points to a different file. – Richard Kettlewell Jan 17 '12 at 19:31
0

fstat the open file, stat the name, and compare the results.

But, in common with any any possible check, it is still racy; the name may change meaning after any check you make but before you act upon it. Time to revisit your requirements.