Convert a delphi function to Lazarus function lazarus / 62-General ---------------------------------------------------------------------- mmgserver · 2018-08-29 11:34 Hello, I'm trying to port a project I'm currently working from Delphi to Lazarus. A key function in the delphi project is the a functions that return into the GUI the response from a console application. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function GetDosOutput(CommandLine: string): string;var  SA: TSecurityAttributes;  SI: TStartupInfo;  PI: TProcessInformation;  StdOutPipeRead, StdOutPipeWrite: THandle;  WasOK: Boolean;  Buffer: array[0..255] of AnsiChar;  BytesRead: Cardinal;  Handle: Boolean;begin  Result := '';  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;    Handle := CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine),                            nil, nil, True, 0, nil,                          nil, 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;  finally    CloseHandle(StdOutPipeRead);  end;end; The Lazarus counterpart that works best in my case appears to be this: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function get_shell_output(const comanda_de_executat:string):string;constREAD_BYTES = 2048; varOutputLines: TStringList;MemStream: TMemoryStream;Process: TProcess;NumBytes: LongInt;BytesRead: LongInt; beginresult:='';// A temp Memorystream is used to buffer the outputMemStream := TMemoryStream.Create;BytesRead := 0; Process := TProcess.Create(nil);//Process.Options := [poUsePipes,poStderrToOutPut];Process.Options := [poUsePipes];Process.ShowWindow := swoHIDE; {$IFDEF Windows}Process.Executable := 'c:\windows\system32\cmd.exe';Process.Pa rameters.Add('/c');Process.Parameters.Add(comanda_de_executat);{$ENDIF Windows}{$IFDEF Unix}Process.Executable := '/bin/ls';Process.Parameter s.Add('-c');Process.Parameters.Add(comanda_de_executat);{$ENDIF Unix} // We cannot use poWaitOnExit here since we don’t// know the size of the output. On Linux the size of the// output pipe is 2 kB; if the output data is more, we// need to read the data. This isn’t possible since we are// waiting. So we get a deadlock here if we use poWaitOnExit. Process.Execute;while Process.Running dobegin// make sure we have roomMemStream.SetSize(BytesRead + READ_BYTES); // try reading itNumBytes := Process.Output.Read((MemStream.Memory + BytesRead)^, READ_BYTES);if NumBytes > 0then beginInc(BytesRead, NumBytes);endelse begin// no data, wait 100 msSleep(100);end;end;// read last partrepeat// make sure we have roomMemStream.SetSize(BytesRead + READ_BYTES);// try reading itNumBytes := Process.Output.Read((MemStream.Memory + BytesRead)^, READ_BYTES);if NumBytes > 0then beginInc(BytesRead, NumBytes);end;until NumBytes=0;MemStream.SetSize(BytesRead); OutputLines := TStringList.Create;OutputLines.LoadFromStream(MemStream); for NumBytes := 0 to OutputLines.Count-1 dobeginresult:=result+slinebreak+OutputLin es[NumBytes];end;OutputLines.Free;Process.Free;MemStream.Free;end; The problem is that function "getdosoutput" is able to capture and return to gui some complex console output while "function get_shell_output" works ok only with commands adressed to cmd. ex: "getdosoutput" return output from this command: psexec \\server1 -u myusername -p mypassword -s -h cmd /c (hostname)^&(ipconfig /all) "get_shell_output" return no output from the command: psexec \\server1 -u myusername -p mypassword -s -h cmd /c (hostname)^&(ipconfig /all) Could someone please enlight me? ---------------------------------------------------------------------- marcov · 2018-08-29 11:41 The first seems to do what poStderrToOutPut (which is commented out) would do in the second, redirect stderr to stdout. But it all looks horribly complex, how about something like: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function GetDosOutput(CommandLine: string): string;begin  runcommand('cmd.exe', ['/C',commandline],result,[poStderrToOutPut]);end; ---------------------------------------------------------------------- mmgserver · 2018-08-29 11:54 Quote from: marcov on August 29, 2018, 01:41:31 pmThe first seems to do what poStderrToOutPut (which is commented out) would do in the second, redirect stderr to stdout. But it all looks horribly complex, how about something like: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function GetDosOutput(CommandLine: string): string;begin  runcommand('cmd.exe', ['/C',commandline],result,[poStderrToOutPut]);end; The output to GUI is exactly as the function I posted. I don't receive the ip data: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i PsExec v2.1 - Execute processes remotelyCopyright (C) 2001-2013 Mark RussinovichSysinternals - www.sysinternals.com  Windows IP Configuration Connecting to server... Starting PSEXESVC service on server... Connecting with PsExec service on server... Starting ipconfig on server... ipconfig exited on server with error code 0. And this the output from the same command runned with delphi function: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i SERVER   Windows IP Configuration      Host Name . . . . . . . . . . . . : server    Primary Dns Suffix  . . . . . . . : 0.0.0.0    Node Type . . . . . . . . . . . . : Hybrid    IP Routing Enabled. . . . . . . . : Yes    WINS Proxy Enabled. . . . . . . . : No    DNS Suffix Search List. . . . . . : test                                             Ethernet adapter x:      Connection-specific DNS Suffix  . : test    Description . . . . . . . . . . . : Adapter    Physical Address. . . . . . . . . : 00-00-00-00-00-00    DHCP Enabled. . . . . . . . . . . : No    Autoconfiguration Enabled . . . . : Yes    IPv4 Address. . . . . . . . . . . : xxx.xxx.xxx.xxx(Preferred)     Subnet Mask . . . . . . . . . . . : xxx.xxx.xxx.xxx    Default Gateway . . . . . . . . . : xxx.xxx.xxx.xxx    DNS Servers . . . . . . . . . . . : xxx.xxx.xxx.xxx                                        xxx.xxx.xxx.xxx    NetBIOS over Tcpip. . . . . . . . : Enabled   Tunnel adapter x2:      Connection-specific DNS Suffix  . :  Description . . . . . . . . . . . : Adapter 2    Physical Address. . . . . . . . . : 00-00-00-00-00-00    DHCP Enabled. . . . . . . . . . . : No    Autoconfiguration Enabled . . . . : Yes    IPv4 Address. . . . . . . . . . . : xxx.xxx.xxx.xxx(Preferred)     Subnet Mask . . . . . . . . . . . : xxx.xxx.xxx.xxx    Default Gateway . . . . . . . . . :     NetBIOS over Tcpip. . . . . . . . : Enabled After more investigation there seems to be a bug mening the console never closes after finishing the task.If I manualy close the console windows I receive the expected data. I found that someone reported this problem on stackoverflow: https://stackoverflow.com/questions/14158870/console-application- never-returns-when-ran-with-tprocess Is there any solution to it? Can the console be closed after running the command? ---------------------------------------------------------------------- marcov · 2018-08-29 12:36 My guess it is the way it makes inheritable pipes. That change is quite old, mantis https://bugs.freepascal.org/view.php?id=19325 The offending code is in process.inc:createpipehandles. That report is a fix for not closing consoles, but has apparently as sideeffect that it is incompatible with the setup you are running. If I have more time I'll test if it is with all pipe output "program x which starts program y" scenarios. It might be that psexecv does something not terribly standard. ---------------------------------------------------------------------- mmgserver · 2018-08-30 08:45 Quote from: marcov on August 29, 2018, 02:36:33 pmMy guess it is the way it makes inheritable pipes. That change is quite old, mantis https://bugs.freepascal.org/view.php?id=19325 The offending code is in process.inc:createpipehandles. That report is a fix for not closing consoles, but has apparently as sideeffect that it is incompatible with the setup you are running. If I have more time I'll test if it is with all pipe output "program x which starts program y" scenarios. It might be that psexecv does something not terribly standard. Thank you for your time and help! I've check the "proces.inc" and indeed has the duplicatehandle function, so as you mentioned this is a prbably a side effect of that workaround. ---------------------------------------------------------------------- marcov · 2022-05-26 13:16 Follow up. For similar problems, new options have been added,probably just before FPC 3.2.0 This provides a workaround has been added for this, This problem has been fixed. In cases like this pass "popassinput" in the options.    Example: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit mainprocesstomemo;// piping problem.// https://forum.lazarus.freepasca l.org/index.php/topic,42385.0/topicseen.html{$mode delphi}{$H+} interface uses  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, Process, Pipes; Type  { TForm1 }   TForm1 = class(TForm)    buipconfig: TButton;    buremoteipconfig: TButton;  Memo1: TMemo;    procedure buipconfigClick(Sender: TObject);    procedure buremoteipconfigClick(Sender: TObject);  private  public    procedure ProcessEvent(Sender,Context : TObject;Status:TRunCommandEventCode;const Message:string);  end; var  Form1: TForm1; implementation {$R *.lfm} { TProcessMemo }Type  TProcessToMemo = class(TProcess)                            public                            fmemo : Tmemo;                          bytesprocessed : integer;                            fstringsadded : integer;                            function ReadInputStream(p:TInputPipeStream;var BytesRead:integer;var DataLength:integer;var Data:string;MaxLoops:integer=10):boolean;override;                        end;   function RunCommandMemo(const exename:TProcessString;const commands:array of TProcessString;out outputstring:string; Options : TProcessOptions = [];SWOptions:TShowWindowOptions=swoNone;memo:TMemo=nil;runrefresh : TOnRunCommandEvent=nil ):boolean;Var    p : TProcessToMemo;    i,    exitstatus : integer;    ErrorString : String;begin  p:=TProcessToMemo.create(nil);  if Options<>[] then    P.Options:=Options - [poRunSuspended,poWaitOnExit];  p.options:=p.options+[poRunIdle];   P.ShowWindow:=SwOptions;  p.Executable:=exename;  if high(commands)>=0 then   for i:=low(commands) to high(commands) do     p.Parameters.add(commands[i]);  p.fmemo:=memo;  p.OnRunCommandEvent:=runrefresh;  try    result:=p.RunCommandLoop(outputstring,errorstring,exitstatus)=0;  finally    p.free;  end;  if exitstatus<>0 then result:=false;end; { TForm1 } procedure TForm1.buipconfigClick(Sender: TObject);var s : string;begin // simple case.  RunCommandMemo('cmd.exe',['/w','/c','ipc onfig'],s,[],swonone,memo1,ProcessEvent);end; procedure TForm1.buremoteipconfigClick(Sender: TObject);var s,cmd : string;begin  cmd := 'psexec \\xxxx -u someuser-p somepass -s -h cmd /c (hostname)^&(ipconfig /all)';  RunCommandMemo('cmd.exe',['/w','/c', cmd],s,[poPassInput,poStderrToOutPut],swonone,memo1,ProcessEvent);  memo1.lines.add(s);end; procedure TForm1.ProcessEvent(Sender, Context: TObject;  Status: TRunCommandEventCode; const Message: string);begin  if status in [RunCommandIdle, RunCommandFinished] then    begin      if status =RunCommandFinished then        begin          memo1.lines.add(' process finished');        end;      if tprocesstomemo(sender).fstringsadded>0 then       begin         tprocesstomemo(sender).fstringsadded:=0;//         memo1.lines.add('H andle:'+inttostr(tprocesstomemo(sender).ProcessHandle));         memo1.refresh;       end;      sleep(10);      application.ProcessMessages;    end;end; { TProcessToMemo }  function TProcessToMemo.ReadInputStream(p:TInputPipeStream;var BytesRead:integer;var DataLength:integer;var Data:string;MaxLoops:integer=10):boolean;var lfpos : integer;    crcorrectedpos:integer;    stradded : integer;    newstr : string;begin  Result:=inherited ReadInputStream(p, BytesRead, DataLength, data, MaxLoops);  if (result) and (bytesread>bytesprocessed)then    begin      stradded:=0;      lfpos:=pos(#10,data,bytesprocessed+1);      while (lfpos<>0) and (lfpos<=bytesread) do        begin          crcorrectedpos:=lfpos;        if (crcorrectedpos>0) and (data[crcorrectedpos-1]=#13) then           dec(crcorrectedpos);          newstr:=copy(data,bytesprocessed+1,crcorrectedpos-bytesprocessed-1);        fmemo.lines.add(newstr);           inc(stradded);          bytesprocessed:=lfpos;          lfpos:=pos(#10,data,bytesprocessed+1);        end;      inc(fstringsadded,stradded); // check idle event.    end;end; end.