views:

340

answers:

4

Hello,

I have a process with an open filehandle to a file. I need to detect if this file has been deleted by another process (there may be a file with the same name in its place). On UNIX I was comparing the inodes of my filehandle and the file-path via stat, but this doesn't work on Win32. How can I do this in Perl?

Thanks,
-Peter

+1  A: 

I'd try comparing size, mtime, and atime; should be very difficult for those to be the same (barring nonsense like, say, stat on a filehandle on win32 giving you the information for the current file in the filesystem regardless of whether your filehandle is on a deleted instance). If it's possible for your file to be deleted and replaced with an identical file multiple times within a given second, and you have to detect this, then you may have to go to an architectural solution like using numbered versions of your file or something.

chaos
+7  A: 

I may be mistaken (I'm not a Windows programmer), but I thought files can't be deleted or replaced when they are opened in Win32, or at least by default it isn't possible.

Leon Timmermans
Yes, as far I know, Windows doesn't allow files that are open to be deleted.
R. Bemrose
Yes, this was the root issue. I've had to work around it by re-opening the file every time it is being written to, and then creating and comparing a unique file id (generated by combining the volume serial #, and file high/low index gotten by the kernel api call: GetFileInformationByHandle).
+1  A: 

Look at the Win32::ChangeNotify package to register for notification of changes to a file or directory. It's also possible to open the file via the Win32API::File package such that it can't be deleted while you have it open (see createFile() and OsFHandleOpen() particularly, as well as the CreateFile() docs on MSDN).

Rob K
+2  A: 

This is a hard problem to solve, especially across both Windows and Unix.

Let's back up. Why are you trying to detect if the file has been replaced? My guess would be that you have some sort of race condition, two programs both trying to write to the same file. Perhaps file locking would help here? Or to use a real database? SQLite and Berkley DB come to mind.

Schwern