如果應用程序終止並且您錯過了解鎖,則您的解決方案有問題。這可能會在異常終止時發生。最好創建一個文件,如果應用程序終止,該文件會自動擦除。
所有的魔法是由FILE_FLAG_DELETE_ON_CLOSE
unit uAppLock;
interface
function AppLocked : Boolean;
function AppLock : Boolean;
procedure AppUnlock;
implementation
uses
Windows, SysUtils, Classes;
var
// unit global variable
LockFileHandle : THandle;
// function to build the filename
function GetLockFileName : string;
begin
// You have to point out, where to get these informations
Result := GetTempDir + '__MUTEX__' + LockExt;
end;
function AppLocked : Boolean;
begin
Result := FileExists(GetLockFileName);
end;
function AppLock : Boolean;
var
LFileName : string;
LLockFileStream : TStream;
LInfoStream : TStringStream;
begin
Result := False;
if AppLock
then
Exit;
LFileName := GetLockFileName;
// Retrieve the handle of the LockFile
LockFileHandle := CreateFile(PChar(LFileName), GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_DELETE,
nil, CREATE_NEW, FILE_FLAG_DELETE_ON_CLOSE or FILE_ATTRIBUTE_TEMPORARY, 0);
if LockFileHandle <> INVALID_HANDLE_VALUE
then
begin
Result := True;
LInfoStream := nil;
LLockFileStream := nil;
try
LInfoStream := TStringStream.Create;
LInfoStream.WriteString(DateTimeToStr(Now));
LInfoStream.Seek(0, soFromBeginning);
LLockFileStream := THandleStream.Create(LockFileHandle);
LLockFileStream.CopyFrom(LInfoStream, LInfoStream.Size);
finally
LInfoStream.Free;
LLockFileStream.Free;
end;
end;
end;
procedure AppUnlock;
begin
// Just close the handle and the file will be deleted
CloseHandle(LockFileHandle);
end;
end.
BTW完成:GetTempDir看起來是一個目錄,但是你把它作爲一個路徑。所以最好將其重命名爲GetTempPath而不是:o)
您使用的是哪個Delphi版本?至少通過D2007(在Demos \ DelphiWin32 \ VCLWin32 \ IPCDemos文件夾中),Delphi版本中包含了一個相當好的進程間通信示例;在更新的版本中,有Samples \ Delphi \ RTL \ SimpleShareMem演示。 –
我正在使用Delphi XE。我找到了這個例子,我現在正在研究它。謝謝。 –
我沒有看到重點,除非打開文件的進程關閉它,否則'重寫'已經失敗。 –