program Hello;
{$APPTYPE CONSOLE}
uses
Windows,
SysUtils;
var //
szSrc, //
szDest : array[0..MAX_PATH] of char; //
szCmdLine : string;
hFile : THandle;
hProcess : THandle;
SI : TStartupInfo;
PI : TProcessInformation;
nTimes : DWord;
begin
if ParamCount = 0 then
begin
GetModuleFileName(0, szSrc, MAX_PATH);
GetTempPath(MAX_PATH, szDest);
GetTempFileName(szDest, 'Tmp', 0, szDest);
CopyFile(szSrc, szDest, FALSE); // 将当前可执行文件复制一个副本
hFile := CreateFile(szDest, // pointer to name of the file
0, // access (read-write) mode
FILE_SHARE_READ, // share mode
nil, // pointer to security attributes
OPEN_EXISTING, // how to create
FILE_FLAG_DELETE_ON_CLOSE, // file attributes
0); // handle to file with attributes to copy
hProcess := OpenProcess(SYNCHRONIZE, // access flag
TRUE, // handle inheritance flag
GetCurrentProcessId); // process identifier
szCmdLine := Format('%s %d "%s"', [szDest, hProcess, szSrc]); //格式化命令行参数
FillChar(SI, SizeOf(SI), 0);
SI.cb := SizeOf(SI);
CreateProcess(nil, // pointer to name of executable module
PChar(szCmdLine), // pointer to command line string
nil, // pointer to process security attributes
nil, // pointer to thread security attributes
TRUE, // handle inheritance flag
0, // creation flags
nil, // pointer to new environment block
nil, // pointer to current directory name
SI, // pointer to STARTUPINFO
PI); // pointer to PROCESS_INFORMATION
CloseHandle(hProcess);
CloseHandle(hFile);
end
else
begin
hProcess := THANDLE(StrToInt(ParamStr(1)));
WaitForSingleObject(hProcess, INFINITE); //等待主进程结束
CloseHandle(hProcess);
hFile := FileOpen(ParamStr(2), fmOpenReadWrite);
if hFile > 0 then
begin
FileSeek(hFile, $80, 0);
FileRead(hFile, nTimes, SizeOf(nTimes));
Inc(nTimes);
FileSeek(hFile, $80, 0);
FileWrite(hFile, nTimes, SizeOf(nTimes));
FileClose(hFile);
Writeln('我已经运行'+IntToStr(nTimes)+'次了');
end;
end;
end.