Linux的一大功能是您可以从命令行执行几乎所有操作。如果我们能够从Delphi应用程序中访问命令行指令,这将为我们提供一个非常强大的系统API。在本视频中,我将向您展示如何从Delphi应用程序访问Linux命令行。
program myls;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
Posix.Base,
Posix.Fcntl;
type
TStreamHandle = pointer;
///
/// Man Page: http://man7.org/linux/man-pages/man3/popen.3.html
///
function popen(const command: MarshaledAString; const _type: MarshaledAString): TStreamHandle; cdecl; external libc name _PU + 'popen';
///
/// Man Page: http://man7.org/linux/man-pages/man3/pclose.3p.html
///
function pclose(filehandle: TStreamHandle): int32; cdecl; external libc name _PU + 'pclose';
///
/// Man Page: http://man7.org/linux/man-pages/man3/fgets.3p.html
///
function fgets(buffer: pointer; size: int32; Stream: TStreamHAndle): pointer; cdecl; external libc name _PU + 'fgets';
///
/// Utility function to return a buffer of ASCII-Z data as a string.
///
function BufferToString( Buffer: pointer; MaxSize: uint32 ): string;
var
cursor: ^uint8;
EndOfBuffer: nativeuint;
begin
Result := '';
if not assigned(Buffer) then begin
exit;
end;
cursor := Buffer;
EndOfBuffer := NativeUint(cursor) + MaxSize;
while (NativeUint(cursor)
Result := Result + chr(cursor^);
cursor := pointer( succ(NativeUInt(cursor)) );
end;
end;
var
Handle: TStreamHandle;
Data: array[0..511] of uint8;
begin
try
Handle := popen('/bin/ls -lart','r');
try
while fgets(@data[0],Sizeof(Data),Handle)<>nil do begin
Write(BufferToString(@Data[0],sizeof(Data)));
end;
finally
pclose(Handle);
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号
执行时间: 0.24725484848022 seconds