home *** CD-ROM | disk | FTP | other *** search
/ Chip 2002 March / Chip_2002-03_cd1.bin / zkuste / delphi / kompon / d5 / cak / CAKDIR.ZIP / ConsoleApp.pas < prev    next >
Pascal/Delphi Source File  |  2001-10-12  |  24KB  |  593 lines

  1. unit ConsoleApp;
  2. interface
  3. uses
  4. {$IFDEF VER90}
  5.   D2ImageHelp,
  6. {$ENDIF}
  7.   SysUtils,
  8.   Classes,
  9.   Windows;
  10.  
  11.  
  12. {30/4/00
  13. This unit demonstrates a GUI application spawning a
  14. console application, and capturing the output of the
  15. console application to display in the GUI application.
  16.  
  17. Any matters arising, questions, comments etc... contact
  18.  
  19. Martin Lafferty
  20. martinl@prel.co.uk
  21.  
  22. Production Robots Engineering Ltd
  23. Box 2290, Wimborne, Dorset, BH21 2YY, England.
  24.  
  25. Background
  26. ----------
  27. This example is based on a similar thing I wrote some years
  28. ago which worked not very well under Win95 and not at all under
  29. Windows NT. If you are one of the many people who wrote to me
  30. asking me about this, I am sorry it has taken me so long to sort
  31. it out. I didn't have a need for it until now, and I have been
  32. busy - you know how it is.
  33.  
  34. The Win32 SDK has a topic called
  35.  
  36. "Creating a Child process with redirected input and output". I tried to
  37. use that as a basis for this work but found it very confusing and could
  38. not really get it to do what I wanted. The code presented here is really
  39. based on information from Richter ("Advanced Windows" ISBN 1-57231-548-2)
  40. notably chapters 2 (Kernel Objects) and chapter 3 (Processes)
  41.  
  42. Running Real-mode Dos applications
  43. ----------------------------------
  44. (Windows NT)
  45. If you try to run a real mode dos application under ConsoleTest, it may be
  46. that the application will execute OK but you will not see any output.
  47. In fact, dos applications are not executed directly, but wrapped in a call
  48. to the command processor cmd.exe. If you run the program DosTest.exe you
  49. might notice that the command line passed to CreateProcess is actually
  50. 'cmd /cdostest' This seems to work OK if the program uses DOS calls for its
  51. output (int 21). If however, you have a smarty-pants application which does
  52. direct screen writes (for example anything compiled with Turbo Pascal using
  53. the 'Crt' unit) then this will not work: the output from the program will
  54. be lost. I expect this could be gotten around but I am not about to start
  55. trying.
  56.  
  57. (Windows 98) (I have not tested on Windows95)
  58. I cannot offer much help with this. If you try to run a realmode dos
  59. application with ConsoleTest, the output will be captured OK, but when the
  60. process terminates the pipe between the parent and child processes does not
  61. seem to get broken (as it should when the child closes its output handle).
  62. This means that ReadFile does not return and the program hangs.
  63. I cannot see any reliable way of getting around this. If you are
  64. absolutely desperate you could try checking so see whether the process
  65. has completed (GetExitCodeProcess) at the end of each Read loop, and
  66. breaking from the read loop if it has. Unfortunately, the time delay
  67. between the last output of the child process and the process terminating
  68. is likely to be significant, and you will still get caught. You could
  69. put a delay in here, but the whole business becomes too horrible to
  70. contemplate. Personally I don't run Windows 95 and I don't run MS-DOS
  71. applications so I don't intend to spend much time on this. If you come
  72. up with an answer, let me know. Don't forget that this problem only
  73. applies to real-mode DOS applications: Win32 console apps are fine.
  74.  
  75. Don't bother trying to run the program via the Win98 command shell
  76. (command.com). It doesn't work.
  77.  
  78. For now, any attempt to run an MSDOS application under 95/98 will fail. If
  79. you try and circumvent this limitation by using a batch file, then the
  80. consequences are down to you. I can tell you now: it won't work (your program
  81. will hang).
  82.  
  83.  
  84. Possible Bug
  85. ------------
  86. Here is an interesting thing that might be bug (but I don't think so)
  87.  
  88. Try this on NT:
  89. Open TestApp.dpr (simple console app, supplied) and compile
  90. Open ConsoleTest.dpr in the Delphi IDE
  91. Enter TestApp as command line.
  92. You should get an output - testapp should return 0.
  93.  
  94. Now without closing down Delphi close ConsoleTest.dpr and reopen TestApp.dpr.
  95. Try to compile and you will get a 'Cannot create output file' error - which
  96. normally indicates that the EXE image is still loaded, but if you check the
  97. process list using the NT Task manager there is no sign of Testapp.exe.
  98.  
  99. If you close Delphi, and restart it, you can compile OK.
  100.  
  101.  
  102. It would be reasonable to assume that a bug in ConsoleTest.dpr was failing to
  103. allow TestApp to terminate properly. I have looked for such a bug, and cannot
  104. find anything. If you run ConsoleTest direct from NT (not in the IDE) then the
  105. problem is not present. You can compile TestApp.dpr quite happily in the IDE
  106. after running the EXE via ConsoleTest running outside the IDE. I am not too
  107. sure what is going on here but it seems to be only a problem when TestApp is
  108. running as a grandchild of Delphi. If you find out more, let me know.
  109.  
  110.  
  111. Defines
  112. -------
  113. DEBUG
  114. This checks the number of read loops and also reports the execution time
  115. of the child process
  116.  
  117. 5/08/00
  118. Fixed problem with w98 - I was using a function (GetBinaryType) which
  119. is not supported in Win98.
  120.  
  121. Also, I was throwing out all NE format files as not suitable, thus
  122. refusing to run 16 bit DPMI apps which may have been OK. I now
  123. delve into the NE header a bit to find out whether the program is
  124. DPMI or Windows.
  125.  
  126. I should make the point that it is not necessary to call
  127. GetExecutableInfo if you are prepared to do without the protection
  128. it offers
  129.  
  130. I also check that the file is not a DLL, although these are generally
  131. linked as GUI anyway.
  132.  
  133. 12/09/00
  134. Fixed bug whereby attempting to read new exe header on dos program raises
  135. IO exception. (Phil Scadden (DSIR) noticed this)
  136.  
  137. It may be that the code that calls ExecConsoleApp may want information
  138. about it, or to terminate it. I have therefore decided to pass the process
  139. handle out with OnNewLine, as well as the new line. The AppOutput parameter
  140. is now optional, as clients may wish to entirely handle the process with
  141. OnNewLine
  142. }
  143.  
  144. type
  145.   TConsoleEvent = procedure(Process: THandle; const OutputLine: String) of object;
  146.  
  147. function ExecConsoleApp(const ApplicationName,
  148.                         Parameters: String;
  149.                         AppOutput: TStrings;     {will receive output of child process}
  150.                         OnNewLine: TConsoleEvent  {if assigned called on each new line}
  151.                         ): DWORD;
  152. {Parameters
  153.   ApplicationName.
  154.   This is passed seperate from Parameters so that the the filetype can be checked
  155.   to ensure it is a suitable application. Under Windows NT you may pass a Win32
  156.   console app, or a DOS app. The function assumes an extension of EXE if one is
  157.   not present and does not search for other extensions. If you want to run a COM
  158.   file then you will have to pass the application name with the extension on.
  159.   ApplicationName does not need to be a full path - the function will round up
  160.   the usual suspects - CurrentDir, SystemDir, SearchPath etc.. See API help for
  161.   SearchPath function.
  162.  
  163.   If you want to run a BAT or CMD you will have to pass the extension.
  164.   ExecConsoleApp does NOT attempt to verify the contents of these files - it
  165.   will just pass them to CreateProcess verbatim. When imbedded in a batch file
  166.   MS-DOS programs seem to work correctly (NT ONLY! don't try this under W9x).
  167.   GUI apps in Batch files will just do their thing normally but they
  168.   will block ExecConsoleApp from returning until closed. You probably don't
  169.   want to do this.
  170.  
  171.   Don't try and pass .lnk or .pif files to the function.
  172.   Pifs will be rejected because I just don't like them. (only kidding - I can't
  173.   get them to work properly) and .lnks will be rejected because I would need to
  174.   use the shell to resolve them and I figure you can do that for yourself.
  175.  
  176.   The Application name is always wrapped in double quotes before being passed on
  177.   to the system so you don't have to do this.
  178.  
  179.   Parameters.
  180.   These are passed on the command line to your child process.
  181.  
  182.   AppOutput.
  183.   This is an initialised TStrings variable which will receive the output from
  184.   the child process.
  185.   Note that ExecConsoleApp approximately simulates the behaviour of a real
  186.   console in that if the output has a CR  without a linefeeds, the output
  187.   will all be continued over the top of the last line. This is only
  188.   a rough simulation (LF without CR are ignored, for example) but seems OK
  189.   for most processes. I don't attempt to simulate output tricks like
  190.   backspacing on a line, nor do I attempt to use an OEM character set.
  191.   (this parameter now optional 12/09/00)
  192.  
  193.   OnNewLine
  194.   The function ExecConsoleApp does not return until the child process has
  195.   finished executing. You may want to update your display while the process
  196.   is running however, so each time there is a newline in the output stream
  197.   this event is called. You might use it to do an update on AppOutput, so the
  198.   user can see the application running.
  199.  
  200.  
  201. NOTE CAREFULLY
  202.   In the case of ExecConsoleApp being unable to run the application it will raise
  203.   an exception of type EInOutError. EInOutError is not really that relevant, I know,
  204.   but I get fed up with creating new exception classes for every little thing, and
  205.   it is convenient to me to use this one. (It will be raised if there is an IO error
  206.   when reading the exe header.
  207.  
  208. BUG
  209.   ExecConsoleApp will always fail if the application being spawned is already
  210.   running. This is not good, but I doubt that it will be a problem very often
  211.   in practice, as the sort of apps being run are not interactive.
  212.   If this is a problem to you write to me and I might fix it.
  213.  
  214. }
  215.  
  216. {this function is used by ExecConsoleApp but might be useful for other purposes}
  217. procedure GetExecutableInfo( const Filename: String; var BinaryType, Subsystem: DWORD);
  218. {Binary Type may return:
  219.  
  220.   The following constants are defined by Windows for the GetBinaryType function
  221.   which doesn't work very well under NT and doesn't work at all under w98/w95
  222.  
  223.   SCS_32BIT_BINARY = 0;  A Win32-based application
  224.   SCS_DOS_BINARY = 1;    An MS-DOS - based application
  225.   SCS_WOW_BINARY = 2;    A 16-bit Windows-based application
  226.   SCS_PIF_BINARY = 3;    A PIF file that executes an MS-DOS - based application
  227.   SCS_POSIX_BINARY = 4;  A POSIX - based application
  228.   SCS_OS216_BINARY = 5;  A 16-bit OS/2-based application (NE, not LE (mgl))
  229.  
  230.   I need some more}
  231. const
  232.   SCS_VXD_BINARY = 6;  {linear executable. Could be OS/2. NT thinks DOS!}
  233.   SCS_WIN32_DLL = 7;
  234.   SCS_DPMI_BINARY = 8; {guessing a bit here. Based on NE header loader flags}
  235.  
  236. { Subsystem May return:
  237.  
  238.   IMAGE_SUBSYSTEM_UNKNOWN = 0;      Unknown subsystem
  239.   IMAGE_SUBSYSTEM_NATIVE = 1;       Image doesn't require a subsystem. Probably
  240.                                      a kernel mode device driver
  241.   IMAGE_SUBSYSTEM_WINDOWS_GUI = 2;  Image runs in the Windows GUI subsystem.
  242.   IMAGE_SUBSYSTEM_WINDOWS_CUI = 3;  Image runs in the Windows character subsystem.
  243.   IMAGE_SUBSYSTEM_OS2_CUI = 5;      Image runs in the OS/2 character subsystem.
  244.   IMAGE_SUBSYSTEM_POSIX_CUI = 7;    Image runs in the Posix character subsystem.
  245.   IMAGE_SUBSYSTEM_RESERVED8 = 8;    Image runs in the 8 subsystem.
  246.  
  247. }
  248.  
  249.  
  250. implementation
  251.  
  252.  
  253. procedure GetExecutableInfo( const Filename: String; var BinaryType, Subsystem: DWORD);
  254. var
  255.   f: File;
  256.   ImageDosHeader: IMAGE_DOS_HEADER;
  257.   ImageFileHeader: IMAGE_FILE_HEADER;
  258.   ImageOptionalHeader: IMAGE_OPTIONAL_HEADER;
  259.   Signature: DWORD;
  260.   NEType: Byte;
  261.  
  262. begin
  263.   AssignFile(f, Filename);
  264.   Reset(f, 1); {note that this will fail if file is open. this is a bug really,
  265.                 but not a big one. Use Api File calls to work around}
  266.   try
  267.     BlockRead(f, ImageDosHeader, Sizeof(ImageDosHeader));
  268.     if (ImageDosHeader.e_magic <> IMAGE_DOS_SIGNATURE) then {not executable}
  269.       raise EInOutError.Create('Dos signature not present');
  270.     try   {16 bit dos program might not have new header}
  271.       Seek(f, ImageDosHeader._lfanew);
  272.       BlockRead(f, Signature, SizeOf(Signature));
  273.       Signature:= Signature and $FFFF;
  274.     except
  275.       on EInOutError do
  276.         Signature:= 0
  277.     end;
  278.     case Signature of
  279.       IMAGE_OS2_SIGNATURE: {New Executable}
  280.       begin
  281.         Seek(f, FilePos(f) + $32); {loader flags are $36 bytes into NE header, but we
  282.                                     have already read 4 bytes for PE signature}
  283.         BlockRead(f, NEType, SizeOf(NEType));
  284.         case NEType of
  285.           1: BinaryType:= SCS_DPMI_BINARY;  {guessing a bit here}
  286.           2: BinaryType:= SCS_WOW_BINARY;
  287.         else
  288.           BinaryType:= SCS_OS216_BINARY; {presumably. I don't have one to check the loader flags!}
  289.         end
  290.       end;
  291.       IMAGE_OS2_SIGNATURE_LE: BinaryType:= SCS_VXD_BINARY;
  292.       IMAGE_NT_SIGNATURE: BinaryType:= SCS_32BIT_BINARY;
  293.     else
  294.       BinaryType:= SCS_DOS_BINARY;
  295.     end;
  296.     Subsystem:= IMAGE_SUBSYSTEM_UNKNOWN;
  297.     if (BinaryType = SCS_32BIT_BINARY)then
  298.     begin
  299.       BlockRead(f, ImageFileHeader, SizeOf(ImageFileHeader));
  300.       if (ImageFileHeader.Characteristics and IMAGE_FILE_EXECUTABLE_IMAGE) = 0 then
  301.         raise EInOutError.Create('File is not executable');  {could be COFF obj}
  302.       if (ImageFileHeader.Characteristics and IMAGE_FILE_DLL) = IMAGE_FILE_DLL then
  303.       begin
  304.         BinaryType:= SCS_WIN32_DLL
  305.       end else
  306.       begin
  307.         BlockRead(f, ImageOptionalHeader, SizeOf(ImageOptionalHeader));
  308.         Subsystem:= ImageOptionalHeader.Subsystem
  309.       end
  310.     end
  311.   finally
  312.     CloseFile(f)
  313.   end
  314. end;
  315.  
  316. function ExecConsoleApp(const ApplicationName, Parameters: String;
  317.                         AppOutput: TStrings;     {will receive output of child process}
  318.                         OnNewLine: TConsoleEvent  {if assigned called on each new line}
  319.                         ): DWORD;
  320.  
  321. {we assume that child process requires no input. I have not thought about the
  322. possible consequences of this assumption. I expect we could come up with some
  323. sort of tricky console IO thingy - but we would need to either run an auxilliary
  324. thread or process windows messages somewhere.
  325.  
  326. This function returns exit code of child process (normally 0 for no error)
  327.  
  328. If the function returns STILL_ACTIVE ($00000103) then the ReadLoop
  329. has terminated before the app has finished executing. See comments in body
  330. of function
  331. }
  332.  
  333. const
  334.   CR = #$0D;
  335.   LF = #$0A;
  336.   TerminationWaitTime = 5000;
  337.   ExeExt = '.EXE';
  338.   ComExt = '.COM'; {the original dot com}
  339.  
  340. var
  341.   StartupInfo:TStartupInfo;
  342.   ProcessInfo:TProcessInformation;
  343.   SecurityAttributes: TSecurityAttributes;
  344.  
  345.   TempHandle,
  346.   WriteHandle,
  347.   ReadHandle: THandle;
  348.   ReadBuf: array[0..$100] of Char;
  349. {$IFDEF VER90}
  350.   BytesRead: Integer;
  351. {$ELSE}
  352.   BytesRead: Cardinal;
  353. {$ENDIF}
  354.   LineBuf: array[0..$100] of Char;
  355.   LineBufPtr: Integer;
  356.   Newline: Boolean;
  357.   i: Integer;
  358.   BinType, SubSyst: DWORD;
  359.  
  360.   Ext, CommandLine: String;
  361.   AppNameBuf: array[0..MAX_PATH] of Char;
  362.   ExeName: PChar;
  363.  
  364. {$IFDEF DEBUG}
  365.   ReadCount: Integer;
  366.   StartExec,
  367.   EndExec,
  368.   PerfFreq: Int64;
  369. {$ENDIF}
  370.  
  371. procedure OutputLine;
  372. begin
  373.   LineBuf[LineBufPtr]:= #0;
  374.   if Assigned(AppOutput) then
  375.   with AppOutput do
  376.   begin
  377.     if Newline then
  378.       Add(LineBuf)
  379.     else
  380.       Strings[Count-1]:= LineBuf  {should never happen with count = 0}
  381.   end;
  382.   Newline:= false;
  383.   LineBufPtr:= 0;
  384.   if Assigned(OnNewLine) then
  385.     OnNewLine(ProcessInfo.hProcess, LineBuf)
  386. end;
  387.  
  388. begin
  389.   {Find out about app}
  390.   Ext:= UpperCase(ExtractFileExt(ApplicationName));
  391.   if (Ext = '.BAT') or ((Win32Platform = VER_PLATFORM_WIN32_NT) and (Ext = '.CMD')) then
  392.   begin {just have a bash}
  393.     FmtStr(CommandLine, '"%s" %s', [ApplicationName, Parameters])
  394.   end else
  395.   if (Ext = '') or (Ext = ExeExt) or (Ext = ComExt) then  {locate and test the application}
  396.   begin
  397.     if SearchPath(nil, PChar(ApplicationName), ExeExt, SizeOf(AppNameBuf), AppNameBuf, ExeName) = 0 then
  398.       raise EInOutError.CreateFmt('Could not find file %s', [ApplicationName]);
  399.     if Ext = ComExt then
  400.       BinType:= SCS_DOS_BINARY
  401.       {in fact, there is no way of telling, but we will just try to run the program. NT is
  402.       equally ignorant and will blindly run anything with a .COM extension}
  403.     else
  404.       GetExecutableInfo(AppNameBuf, BinType, SubSyst);
  405.     if ((BinType = SCS_DOS_BINARY) or (BinType = SCS_DPMI_BINARY)) and
  406.         (Win32Platform = VER_PLATFORM_WIN32_NT) then
  407.       FmtStr(CommandLine, 'cmd /c""%s" %s"', [AppNameBuf, Parameters])
  408.     else
  409.     if (BinType = SCS_32BIT_BINARY) and (SubSyst = IMAGE_SUBSYSTEM_WINDOWS_CUI) then
  410.       FmtStr(CommandLine, '"%s" %s', [AppNameBuf, Parameters])
  411.     else
  412.       raise EInOutError.Create('Executable image is not a supported type')
  413.             {Supported types are Win32 Console or MSDOS under Windows NT only}
  414.   end else
  415.   begin
  416.     raise EInOutError.CreateFmt('%s has invalid file extension', [ApplicationName])
  417.   end;
  418.  
  419.   FillChar(StartupInfo,SizeOf(StartupInfo), 0);
  420.   FillChar(ReadBuf, SizeOf(ReadBuf), 0);
  421.   FillChar(SecurityAttributes, SizeOf(SecurityAttributes), 0);
  422. {$IFDEF DEBUG}
  423.   ReadCount:= 0;
  424.   if QueryPerformanceFrequency(PerfFreq) then
  425.     QueryPerformanceCounter(StartExec);
  426. {$ENDIF}
  427.   LineBufPtr:= 0;
  428.   Newline:= true;
  429.   with SecurityAttributes do
  430.   begin
  431.     nLength:= Sizeof(SecurityAttributes);
  432.     bInheritHandle:= true
  433.   end;
  434.   if not CreatePipe(ReadHandle, WriteHandle, @SecurityAttributes, 0) then
  435.     RaiseLastWin32Error;
  436.   {create a pipe to act as StdOut for the child. The write end will need
  437.    to be inherited by the child process}
  438.   try
  439.     {Read end should not be inherited by child process}
  440.     if Win32Platform = VER_PLATFORM_WIN32_NT then
  441.     begin
  442.       if not SetHandleInformation(ReadHandle, HANDLE_FLAG_INHERIT, 0) then
  443.         RaiseLastWin32Error
  444.     end else
  445.     begin
  446.       {SetHandleInformation does not work under Window95, so we
  447.       have to make a copy then close the original}
  448.       if not DuplicateHandle(GetCurrentProcess, ReadHandle,
  449.         GetCurrentProcess, @TempHandle, 0, True, DUPLICATE_SAME_ACCESS) then
  450.         RaiseLastWin32Error;
  451.       CloseHandle(ReadHandle);
  452.       ReadHandle:= TempHandle
  453.     end;
  454.  
  455.     with StartupInfo do
  456.     begin
  457.       cb:= SizeOf(StartupInfo);
  458.       dwFlags:= STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
  459.       wShowWindow:= SW_HIDE;
  460.       hStdOutput:= WriteHandle
  461.     end;
  462.     {StartupInfo provides additional parameters to CreateProcess.
  463.     I suspect that it is only safe to pass WriteHandle as hStdOutput
  464.     because we are going to make sure that the child inherits it.
  465.     This is not documented anywhere, but I am reasonably sure it is
  466.     correct. It is (mildly) interesting to note that the example
  467.     given in Win32.hlp "Creating a Child process with redirected
  468.     input and output" does not set the 'StdHandle' fields of StartupInfo.
  469.     Instead the parent process sets its own StdInput and StdOutput
  470.     handles prior to creating the child process - Apparently, the child
  471.     process will then use these values. It all seems a bit odd to me,
  472.     given that a much simpler mechanism (Handle fields of StartupInfo)
  473.     seems to have been provided. Anyway, this alternative approach does
  474.     not seem to work when the parent process is GUI-based. Perhaps Windows
  475.     ignores SetStdHandle for a GUI app.
  476.  
  477.     We should not have to use STARTF_USESHOWWINDOW and
  478.     wShowWindow:= SW_HIDE as we are going to tell CreateProcess not to
  479.     bother with an output window, but it would appear that Windows 95
  480.     ignores the CREATE_NO_WINDOW flag. Fair enough - it is not in the SDK
  481.     documentation (I got it out of Richter). CREATE_NO_WINDOW actually makes
  482.     virtually no difference to the execution time of my 'hello world' test
  483.     program, but it seems the correct thing to do.
  484.  
  485.     I shouldn't bother with the DETACHED_PROCESS flag. I suspect that it is
  486.     only relevant when the calling process is a console app.
  487.     }
  488.  
  489.     if not CreateProcess(nil, PChar(CommandLine),
  490.        nil, nil,
  491.        true,                   {inherit kernel object handles from parent}
  492.        CREATE_NO_WINDOW,
  493.        nil,
  494.        nil,
  495.        StartupInfo,
  496.        ProcessInfo) then
  497.      RaiseLastWin32Error;
  498.  
  499.     CloseHandle(ProcessInfo.hThread);
  500.     {not interested in threadhandle - close it}
  501.  
  502.     CloseHandle(WriteHandle);
  503.     {close our copy of Write handle - Child has its own copy now. It is important
  504.     to close ours, otherwise ReadFile may not return when child closes its
  505.     StdOutput - this is the mechanism by which the following loop detects the
  506.     termination of the child process: it does not poll GetExitCodeProcess.
  507.  
  508.     The clue to this behaviour is in the 'Anonymous Pipes' topic of Win32.hlp - quote
  509.  
  510.     "To read from the pipe, a process uses the read handle in a call to the
  511.     ReadFile function. When a write operation of any number of bytes completes,
  512.     the ReadFile call returns. The ReadFile call also returns when all handles
  513.     to the write end of the pipe have been closed or if any errors occur before
  514.     the read operation completes normally."
  515.  
  516.     On this basis (and going somewhat beyond that stated above) I have assumed that
  517.     ReadFile will return TRUE when a write is completed at the other end of the pipe
  518.     and will return FALSE when the write handle is closed at the other end.
  519.  
  520.     I have also assumed that ReadFile will return when its output buffer is full
  521.     regardless of the size of the write at the other end.
  522.  
  523.     I have tested all these assumptions as best I can (under NT 4)}
  524.  
  525.     try
  526.       while ReadFile(ReadHandle, ReadBuf, SizeOf(ReadBuf), BytesRead, nil) do
  527.       begin
  528.         {There are much more efficient ways of doing this: we don't really
  529.         need two buffers, but we do need to scan for CR & LF &&&}
  530. {$IFDEF Debug}
  531.         Inc(ReadCount);
  532. {$ENDIF}
  533.         for  i:= 0 to BytesRead - 1 do
  534.         begin
  535.           if (ReadBuf[i] = LF) then
  536.           begin
  537.             Newline:= true
  538.           end else
  539.           if (ReadBuf[i] = CR) then
  540.           begin
  541.             OutputLine
  542.           end else
  543.           begin
  544.             LineBuf[LineBufPtr]:= ReadBuf[i];
  545.             Inc(LineBufPtr);
  546.             if LineBufPtr >= (SizeOf(LineBuf) - 1) then {line too long - force a break}
  547.             begin
  548.               Newline:= true;
  549.               OutputLine
  550.             end
  551.           end
  552.         end
  553.       end;
  554.       WaitForSingleObject(ProcessInfo.hProcess, TerminationWaitTime);
  555.       {The child process may have closed its StdOutput handle but not yet
  556.       terminated, so will wait for up to five seconds to give it a chance to
  557.       terminate. If it has not done so after this time, then we will end
  558.       up returning STILL_ACTIVE ($103)
  559.  
  560.       If you don't care about the exit code of the process, then you don't
  561.       need this wait: having said that, unless the child process has a
  562.       particularly longwinded cleanup routine, the wait will be very short
  563.       in any event.
  564.       I recommend you leave this wait in place unless you have an intimate
  565.       understanding of the child process you are spawining and are sure you
  566.       don't want to wait for it}
  567.  
  568.       GetExitCodeProcess(ProcessInfo.hProcess, Result);
  569.       OutputLine {flush the line buffer}
  570.  
  571. {$IFDEF DEBUG} ;  {that's how much I dislike null statements!
  572.                    Is there a nobel prize for pedantry?}
  573.       if (PerfFreq > 0) and Assigned(AppOutput) then
  574.       begin
  575.         QueryPerformanceCounter(EndExec);
  576.         AppOutput.Add(Format('Debug: (readcount = %d), ExecTime = %.3f ms',
  577.             [ReadCount, ((EndExec - StartExec)*1000.0)/PerfFreq]))
  578.       end else
  579.       begin
  580.         AppOutput.Add(Format('Debug: (readcount = %d)', [ReadCount]))
  581.       end
  582. {$ENDIF}
  583.     finally
  584.       CloseHandle(ProcessInfo.hProcess)
  585.     end
  586.   finally
  587.     CloseHandle(ReadHandle)
  588.   end
  589. end;
  590.  
  591.  
  592. end.
  593.