Delphi 在Windows和Linux下执行命令并返回结果的代码  
官方Delphi 学习QQ群: 682628230(三千人)
频道

Delphi 在Windows和Linux下执行命令并返回结果的代码


 以前有一个Delphi7版本的方法,用这个实现了VisualSVNServer的分级授权管理,现在要同时支持Windows和Linux的SVN分级授权管理。查阅网上资料实现了适用于两个操作系统的代码:


引入Linux下需要使用到的单元:


{$IFDEF POSIX} Posix.Base, Posix.Fcntl, {$ENDIF}


执行命令行并返回结果的代码:


{$IFDEF MSWINDOWS}

function TBaseUtils.runCommand(Command: string; RunDir: string; var strErrMsg: string): string;

var

  SA: TSecurityAttributes;

  SI: TStartupInfo;

  PI: TProcessInformation;

  StdOutPipeRead, StdOutPipeWrite: THandle;

  WasOK: Boolean;

  Buffer: array[0..255] of AnsiChar;

  BytesRead: Cardinal;

  WorkDir: string;

  Handle: Boolean;

begin

  Result := '';

  try

    with SA do

      begin

        nLength := SizeOf(SA);

        bInheritHandle := True;

        lpSecurityDescriptor := nil;

      end;

    CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0);

    try

      with SI do

        begin

          FillChar(SI, SizeOf(SI), 0);

          cb := SizeOf(SI);

          dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;

          wShowWindow := SW_HIDE;

          hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin

          hStdOutput := StdOutPipeWrite;

          hStdError := StdOutPipeWrite;

        end;

      WorkDir := RunDir;

      Handle := CreateProcess(nil, PChar('cmd.exe /C ' + command), nil, nil, True, 0, nil, PChar(WorkDir), SI, PI);

      CloseHandle(StdOutPipeWrite);

      if Handle then

        try

          repeat

            WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil);

            if BytesRead > 0 then

              begin

                Buffer[BytesRead] := #0;

                Result := Result + Buffer;

              end;

          until not WasOK or (BytesRead = 0);

          WaitForSingleObject(PI.hProcess, INFINITE);

        finally

          CloseHandle(PI.hThread);

          CloseHandle(PI.hProcess);

        end;

    except

      on E: Exception do

        strErrMsg := E.ClassName + ': ' + E.Message;

    end;

  finally

    CloseHandle(StdOutPipeRead);

  end;

end;

{$ENDIF}

 

{$IFDEF POSIX}

type

  TStreamHandle = pointer;

function popen(const command: PAnsiChar; const _type: PAnsiChar): 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 TBaseUtils.runCommand(Command: string; RunDir: string; var strErrMsg: string): string;

var

  Handle: TStreamHandle;

  Data: array[0..511] of uint8;

  acommand : PAnsiChar;

  sReturn : string;

begin

  Result := '';

  try

    acommand := PAnsiChar(AnsiString(command));

    Handle := popen(acommand, 'r');

    sReturn := '';

    try

      while fgets(@Data[0], Sizeof(Data), Handle) <> nil do

        sReturn := sReturn + Utf8ToString(@Data[0]);

    finally

      pclose(Handle);

    end;

    Result := sReturn;

  except

    on E: Exception do

      strErrMsg := E.ClassName + ': ' + E.Message;

  end;

end;

{$ENDIF POSIX}

测试代码:


  Writeln('-----------执行命令行-----------');

  {$IFDEF MSWINDOWS} cmdLine := '"dir D:\"'; {$ENDIF}

  {$IFDEF POSIX}     cmdLine := 'ls -l /';   {$ENDIF}

  sDest := gFun.runCommand(cmdLine,'d:\',strErrMsg);

  if sDest<>'' then

    Writeln('runCommand:'+sDest)

  else

    Writeln('runCommand Error:'+strErrMsg);

 

————————————————


原文链接:https://blog.csdn.net/iivii/article/details/103438406



推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号

执行时间: 0.17372298240662 seconds