Как узнать расход памяти процессом?

Материал из DRKB


Расход памяти можно прочитать из виртуального файла

/proc/Pid/status

где Pid - номер процесса

function ReadProcData(Pid: string; var VmSize, VmLck, VmRSS, VmData, VmStk, VmExe, VmLib, ProcName: string): Boolean;
var
  f: TextFile;
  s, stat: string;
  i: Integer;

  function GetBefore(subStr, str: string): string;
  begin
    if Pos(subStr, str) > 0 then
      Result := Copy(str, 1, Pos(subStr, str)-1)
    else
      Result := '';
  end;

  function GetAfter(subStr, str: string): string;
  begin
    if Pos(subStr, str) > 0 then
      Result := Copy(str, Pos(subStr, str) + Length(subStr), Length(str))
    else
      Result := '';
  end;

begin
  Result := False;
  FileMode := 0;
  VmSize := '-1';
  VmLck := '-1';
  VmRSS := '-1';
  VmData := '-1';
  VmStk := '-1';
  VmExe := '-1';
  VmLib := '-1';
  ProcName := '';
  try
    try
      try
        AssignFile(f, '/proc/' + Pid + '/status');
        Reset(f);
        while not Eof(f) do
        begin
          ReadLn(f, s);
          if Pos('VmSize', s) > 0 then VmSize := GetBefore(' ', Trim(GetAfter(':', s)));
          if Pos('VmLck', s) > 0 then VmLck := GetBefore(' ', Trim(GetAfter(':', s)));
          if Pos('VmRSS', s) > 0 then VmRSS := GetBefore(' ', Trim(GetAfter(':', s)));
          if Pos('VmData', s) > 0 then VmData := GetBefore(' ', Trim(GetAfter(':', s)));
          if Pos('VmStk', s) > 0 then VmStk := GetBefore(' ', Trim(GetAfter(':', s)));
          if Pos('VmExe', s) > 0 then VmExe := GetBefore(' ', Trim(GetAfter(':', s)));
          if Pos('VmLib', s) > 0 then VmLib := GetBefore(' ', Trim(GetAfter(':', s)));
          if Pos('Name', s) > 0 then ProcName := Trim(GetAfter(':', s));
        end;
      finally
        CloseFile(f);
      end;
    finally
      FileMode := 2;
    end;
    Result := True;
  except
  end;
end;


Примечание - функция может и не сработать, какие-то мгновения файл недоступен по чтению, выход - повторить процедуру.

Более подробную информацию можно получить запустив в консоли:

man proc


Author: Vit
ID: 04627