Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to effectively wait for a file to unlock?

Tags:

winapi

delphi

In my thread code I need to wait for a file to be unlocked in order to process it further.

The file is potentially locked by another foreign thread(s) which I can't control.

Currently i use this code in my thread:

...
while IsFileInUse(FileName) and not Terminated do
begin
  Sleep(100);
end;
// process the file

IsFileInUse code:

function IsFileInUse(const FileName: string): Boolean;
var
  Handle: HFILE;
begin
  Handle := CreateFile(PChar(FileName),
    GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  Result := (Handle = INVALID_HANDLE_VALUE);
  if not Result then
    CloseHandle(Handle);
end;

Is there a better and more efficient way to avoid the Sleep?

like image 705
zig Avatar asked Dec 20 '18 12:12

zig


1 Answers

No, there is no API that would make it possible to be notified when opening a file becomes possible. Programs that monitor this kind of activity (e.g. ProcessMonitor) use a file system driver (link).

Consider giving up on a test opening of the file though, as it introduces a possibility that the file becomes unavailable again in between a test opening and actual opening for processing.

like image 128
Sertac Akyuz Avatar answered Nov 08 '22 17:11

Sertac Akyuz