本文作者:icy

Delphi-Linux-Command[Delphi在linux下执行命令]

icy 2021-09-30 1533 抢沙发
Delphi-Linux-Command[Delphi在linux下执行命令]摘要: 忽然在自己的路由器外界usb上翻到的,两年前在单位弄的 传回家的 嘿嘿unit Ice.CommandLS;interfaceuses &nbs...

忽然在自己的路由器外界usb上翻到的,两年前在单位弄的 传回家的 嘿嘿

unit Ice.CommandLS;

interface
uses
  System.SysUtils,
  System.Classes,
  Posix.Base,
  Posix.Fcntl;
{------------------------------------------------------------------------------}
procedure CommandExec(OnStop:  TProc; const Command: MarshaledAString);
implementation
{------------------------------------------------------------------------------}

type TStreamHandle = pointer;
function popen(const command: MarshaledAString; const _type: MarshaledAString): TStreamHandle; cdecl; external libc name _PU + 'popen';
function pclose(filehandle: TStreamHandle): int32; cdecl; external libc name _PU + 'pclose';
function fgets(buffer: pointer; size: int32; Stream: TStreamHAndle): pointer; cdecl; external libc name _PU + 'fgets';
function BufferToString( Buffer: pointer; MaxSize: uint32 ): string;
var
  cursor: ^uint8;
  EndOfBuffer: nativeuint;
begin
  Result:= '';
  if not assigned(Buffer) then exit;
  EndOfBuffer:= NativeUint(cursor) + MaxSize;
  cursor:= Buffer;
  while ( NativeUint(cursor) < EndOfBuffer ) and ( cursor^ <> 0 ) do
  begin
    Result:= Result + chr(cursor^);
    cursor:= pointer( succ(NativeUInt(cursor)) );
  end;
end;

procedure CommandExec(OnStop:  TProc; const Command: MarshaledAString);
var
  Handle: TStreamHandle;
  Data: array[0..511] of uint8;
begin
  Handle := popen(command,'r');
  try
    while fgets(@data[0],Sizeof(Data),Handle) <> nil do
      Write(BufferToString(@Data[0],sizeof(Data)));


    if Assigned(OnStop) then
       OnStop;
  finally
    pclose(Handle);
  end;
end;

end.


觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

分享

发表评论

快捷回复:

评论列表 (暂无评论,1533人围观)参与讨论

还没有评论,来说两句吧...