gpt4 book ai didi

delphi - 仅知道服务名称即可获取服务的内存信息

转载 作者:行者123 更新时间:2023-12-01 23:07:39 24 4
gpt4 key购买 nike

有没有办法只知道服务名称就可以获取服务应用程序使用了多少内存?

最佳答案

首先,您必须使用 QueryServiceStatusEx 检索与服务关联的进程的 Pid函数或 Win32_Service然后你可以使用WMI类GetProcessMemoryInfo函数收集进程的内存使用信息。

检查此示例应用程序

{$APPTYPE CONSOLE}

uses
ActiveX,
ComObj,
Variants,
Windows,
psApi,
SysUtils;

function GetPidFromService(const ServiceName : string) : DWORD;
const
WbemUser ='';
WbemPassword ='';
WbemComputer ='localhost';
wbemFlagForwardOnly = $00000020;
var
FSWbemLocator : OLEVariant;
FWMIService : OLEVariant;
FWbemObjectSet: OLEVariant;
FWbemObject : OLEVariant;
oEnum : IEnumvariant;
iValue : LongWord;
begin;
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
FWMIService := FSWbemLocator.ConnectServer(WbemComputer, 'root\CIMV2', WbemUser, WbemPassword);
FWbemObjectSet:= FWMIService.ExecQuery(Format('SELECT ProcessId FROM Win32_Service Where Name="%s"',[ServiceName]),'WQL',wbemFlagForwardOnly);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
if oEnum.Next(1, FWbemObject, iValue) = 0 then
Result:=FWbemObject.ProcessId;
end;

procedure MemoryInfoService(const ServiceName : string);
var
hProcess : THandle;
ppsmemCounters: PPROCESS_MEMORY_COUNTERS;
cb: DWORD;
begin
hProcess := OpenProcess(PROCESS_VM_READ or PROCESS_QUERY_INFORMATION, False, GetPidFromService(ServiceName));
if hProcess <> 0 then
try
cb:=SizeOf(PROCESS_MEMORY_COUNTERS);
GetMem(ppsmemCounters, cb);
try
if GetProcessMemoryInfo( hProcess, ppsmemCounters, cb) then
begin
Writeln( Format('PageFaultCount: %d',[ ppsmemCounters.PageFaultCount]));
Writeln( Format('PeakWorkingSetSize: %d',[ ppsmemCounters.PeakWorkingSetSize]));
Writeln( Format('WorkingSetSize: %d',[ ppsmemCounters.WorkingSetSize]));
Writeln( Format('QuotaPeakPagedPoolUsage: %d',[ ppsmemCounters.QuotaPeakPagedPoolUsage]));
Writeln( Format('QuotaPagedPoolUsage: %d',[ ppsmemCounters.QuotaPagedPoolUsage]));
Writeln( Format('QuotaPeakNonPagedPoolUsage: %d',[ ppsmemCounters.QuotaPeakNonPagedPoolUsage]));
Writeln( Format('PagefileUsage: %d',[ ppsmemCounters.PagefileUsage]));
Writeln( Format('PeakPagefileUsage: %d',[ ppsmemCounters.PeakPagefileUsage]));
end;
finally
FreeMem(ppsmemCounters);
end;
finally
CloseHandle(hProcess);
end;
end;

begin
try
CoInitialize(nil);
try
MemoryInfoService('FirebirdGuardianDefaultInstance');
finally
CoUninitialize;
end;
except
on E:EOleException do
Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.

关于delphi - 仅知道服务名称即可获取服务的内存信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11197330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com