Question

How to Redirect stdout/stderr from a spawned process to application?

Asked by: swift99

I'm trying to encapsulate a call to create a shell process and capture its stdout/stderr from named pipes for further processing.  

I can capture the stdout from a separately started process, but not one spawned from within the application.  I suspect (very strongly) that I am missing a flag or setting for CreateProcess that would allow this.  That is, if I start the process from a command line with "ipconfig > \\.\pipe\{whatever-the-id-is}" I get the stdout when I read the stream.  However, if I start the process with CreateProcess I do not.

Here's the encapsulation code:

unit ShellEncapsulation;

interface

uses Classes, Sysutils, Windows, ShellAPI;

type
  TShell = class (TObject)
  private
    FExecResults: Boolean;
    FStdErrName: String;
    FCommandLine: String;
    FStdOutName: String;
    FStderr: TStream;
    FStdout: TStream;
    hStdErr: THandle;
    hStdOut: THandle;
    Fbuffersize: Integer;
    FTimeOut: Integer;

    procedure SetCommandLine(const Value: String);
    procedure SetExecResults(const Value: Boolean);
    procedure SetStderr(const Value: TStream);
    procedure SetStdErrName(const Value: String);
    procedure SetStdout(const Value: TStream);
    procedure SetStdOutName(const Value: String);
    procedure Setbuffersize(const Value: Integer);
    procedure SetTimeOut(const Value: Integer);
  protected
    function GetUniqueName: String;

    property CommandLine: String read FCommandLine write SetCommandLine;
    property StdErrName: String read FStdErrName write SetStdErrName;
    property StdOutName: String read FStdOutName write SetStdOutName;
  public
    Constructor Create;
    Destructor Done;

    function Exec (_Commandline: String): Boolean;

    property Stdout: TStream read FStdout write SetStdout;
    property Stderr: TStream read FStderr write SetStderr;
    property ExecResults: Boolean read FExecResults write SetExecResults;
    property buffersize: Integer read Fbuffersize write Setbuffersize;
    property TimeOut: Integer read FTimeOut write SetTimeOut;
  end;

implementation

{ TShell }

constructor TShell.Create;
begin
  buffersize := 1024 * 1024;  // Allow 1MB Buffer
  Timeout := 10000;           // Allow 10 seconds time out
end;

destructor TShell.Done;
begin
//  StdOut.Close;
  StdOut.Free;
  StdOut := NIL;
  DisconnectNamedPipe (hStdout);
//  DeleteFile (StdOutName);


//  StdErr.Close
  StdErr.Free;
  StdErr := Nil;
  DisconnectNamedPipe (hStderr);
//  DeleteFile (StdErrName);
end;

function TShell.Exec(_Commandline: String): Boolean;
var
  StartUpInfo : TStartUpInfo;
  ProcessInfo : TProcessInformation;
  cmdLine: String;
begin
  stdoutname := GetUniquename;
  stderrname := GetUniquename;

  hStdOut := CreateNamedPipe (PChar(stdOutName),
    PIPE_ACCESS_INBOUND,
    PIPE_TYPE_BYTE+PIPE_WAIT,
    99,
    bufferSize,
    bufferSize,
    TimeOut,
    NIL);

  hStdErr := CreateNamedPipe (PChar(stdErrName),
    PIPE_ACCESS_INBOUND,
    PIPE_TYPE_BYTE+PIPE_WAIT,
    99,
    bufferSize,
    bufferSize,
    TimeOut,
    NIL);

  StdOut := THandleStream.Create (hStdOut);
  StdErr := THandleStream.Create (hStdErr);

  FillChar(StartUpInfo, SizeOf(TStartUpInfo), 0);
  with StartUpInfo do begin
    cb          := SizeOf(TStartUpInfo);
    dwFlags     := STARTF_USESTDHANDLES;
    wShowWindow := SW_SHOWDEFAULT;
    hStdOutput  := hStdOut;
    hStdError   := hStdErr;
  end; // with

  ExecResults := CreateProcess(nil,
                PChar(_CommandLine),
                nil,
                nil,
                false,
                DETACHED_PROCESS + NORMAL_PRIORITY_CLASS,
                nil,
                PChar(ExtractFilePath(paramStr(0))),
                StartUpInfo,
                ProcessInfo);
  Result := ExecResults;
end;

function TShell.GetUniqueName: String;
var
  aGUID: TGUID;
begin
  CreateGUID (aGUID);
//  result := '\\.\PIPE\'+Copy (GUIDToString (aGUID),2,8);
  result := '\\.\PIPE\'+GUIDToString (aGUID);
end;

procedure TShell.Setbuffersize(const Value: Integer);
begin
  Fbuffersize := Value;
end;

procedure TShell.SetCommandLine(const Value: String);
begin
  FCommandLine := Value;
end;

procedure TShell.SetExecResults(const Value: Boolean);
begin
  FExecResults := Value;
end;

procedure TShell.SetStderr(const Value: TStream);
begin
  FStderr := Value;
end;

procedure TShell.SetStdErrName(const Value: String);
begin
  FStdErrName := Value;
end;

procedure TShell.SetStdout(const Value: TStream);
begin
  FStdout := Value;
end;

procedure TShell.SetStdOutName(const Value: String);
begin
  FStdOutName := Value;
end;

procedure TShell.SetTimeOut(const Value: Integer);
begin
  FTimeOut := Value;
end;

end.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-07-17 at 14:48:25ID20682069
Tags

stdout

,

redirect

Topic

Delphi Programming

Participating Experts
1
Points
150
Comments
3

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. stdout and stderr in Linux
    UNIXer, Can I redirect the stdout and stderr to a temporary file by the following code ? filename=tmpnam(0); freopen(filename, "w", stderr); freopen(filename, "w", stdout); But, how come I cannot print characters to the original stdout and stderr b...
  2. redirecting stderr in c
    I want to execute a program which outputs to stderr, in a section of c code. I could use popen() to monitor output, but this only pipes stdout back to the calling program. I need to read from stderr to recieve update information until the program has finished executing. Ho...
  3. redirecting STDOUT/STDERR ???
    Hi, I tried redirecting STDOUT to a file using SetStdHandle. It seems that it does not affect the output result of printf. Is there something wrong with what I wrote ??? Isn't this command supposed to send the stdout to my file ? If this command only changes a handle which th...
  4. redirection of stdout & stderr
    I've been trying to redirect output of errors from a script job (through cron) to mailx. This works fine, but I loose the stderr going out to the logfile. Ideally I'd like to get stderr & stdout to a log file AND stderr on it's own to mailx. e.g. /tmp/test > /tmp/test....
  5. Redirecting STDERR and STDOUT in C  using library
    Hi All, I want to execute a binary and trap the stdout and stderr . I don't have the code for the binary. I have got the solution for this on the same list which is working fine. Many Thanks to Dave. Here's the code : ================================= Main Program: /* * Samp...
  6. Redirecting stdout and stderr of MFC GUI Application
    I have an MFC GUI application that uses some DLLs that will sometimes write something to stdout or stderr. I would like to capture this output and redirect it to a CEdit control I have in a logging window. Can anyone suggest how to do this?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: DragonSlayerPosted on 2003-07-18 at 03:41:10ID: 8950631

Hi swift99, this thing took a couple of my hours... :)

was going thru your code and logically, nothing could be wrong hehehe... tried it again and again, with security attributes, overlapped I/O... none worked.

then I modified a non-OO version of the above code using standard files (CreateFile thingy)... and it worked! duh!

so I put in pipes... and it stopped working again... double duh!

ok to cut a long (and frustrating) story short, I was biting on my Snickers bar, and suddenly decided to try something crazy... you know, handles are handles, right? so there should be no difference between a pipe handle or a file handle... but I decided to give it a try anyway...

    FillChar(SecAttrs, SizeOf(SecAttrs), #0);
    SecAtrrs.nLength              := SizeOf(SecAttrs);
    SecAtrrs.lpSecurityDescriptor := nil;
    SecAtrrs.bInheritHandle       := True;

  StrPCopy(pOutPutFile, OutStreamName); // <-- OutStreamName was generated via GetUniqueName

  if OutStreamHandle <> INVALID_HANDLE_VALUE then
    DisconnectNamedPipe(OutStreamHandle);
  OutStreamHandle := CreateNamedPipe(
    PChar(pOutputFile),
    PIPE_ACCESS_DUPLEX,
    PIPE_TYPE_BYTE or PIPE_WAIT,
    PIPE_UNLIMITED_INSTANCES,
    8192,
    8192,
    10000,
    @SecAttrs);

    hOutputFile := CreateFile(
                              pOutPutFile,                           { pointer to name of the file }
                              GENERIC_READ or GENERIC_WRITE,         { access (read-write) mode }
                              FILE_SHARE_READ or FILE_SHARE_WRITE,   { share mode }
                              @SecAttrs,                             { pointer to security attributes }
                              CREATE_ALWAYS,                         { how to create }
                              FILE_ATTRIBUTE_TEMPORARY,              { file attributes }
                              0 );                                   { handle to file with attributes to copy }

tried it... still didn't work.

so I created an input pipe...

    CreateNamedPipe(
      pInputFile,
    PIPE_ACCESS_DUPLEX,
    PIPE_TYPE_BYTE or PIPE_WAIT,
    PIPE_UNLIMITED_INSTANCES,
    8192,
    8192,
    10000,
    @SecAtrrs);

    { create the appropriate handle for the input file }
    hInputFile := CreateFile(
                             pInputFile,                            { pointer to name of the file }
                             GENERIC_READ or GENERIC_WRITE,         { access (read-write) mode }
                             FILE_SHARE_READ or FILE_SHARE_WRITE,   { share mode }
                             @SecAtrrs,                             { pointer to security attributes }
                             OPEN_ALWAYS,                           { how to create }
                             FILE_ATTRIBUTE_TEMPORARY,              { file attributes }
                             0 );                                   { handle to file with attributes to copy }

    FillChar(StartupInfo, SizeOf(StartupInfo), #0);
    StartupInfo.cb          := SizeOf(StartupInfo);
    StartupInfo.dwFlags     := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
    StartupInfo.wShowWindow := SW_HIDE;
    StartupInfo.hStdOutput  := hOutputFile;
    StartupInfo.hStdInput   := hInputFile; // INVALID_HANDLE_VALUE;

    { create the app }
    Result := CreateProcess(nil,                           { pointer to name of executable module }
                            pCommandLine,                  { pointer to command line string }
                            nil,                           { pointer to process security attributes }
                            nil,                           { pointer to thread security attributes }
                            True,                          { handle inheritance flag }
                            CREATE_NEW_CONSOLE or
                            REALTIME_PRIORITY_CLASS,       { creation flags }
                            nil,                           { pointer to new environment block }
                            nil,                           { pointer to current directory name }
                            StartupInfo,                   { pointer to STARTUPINFO }
                            ProcessInfo);                  { pointer to PROCESS_INF }


and it worked like a charm!

  if OutStreamHandle <> INVALID_HANDLE_VALUE then
  begin
    with THandleStream.Create(OutStreamHandle) do
    try
      Seek(0, soFromBeginning);
      Memo1.Lines.Clear;
      while Position < Size do
      begin
        Read(TextStream, SizeOf(TextStream));
        Memo1.Lines.Add(TextStream);
      end;
    finally
      OutStream.Free;
    end;
  end;

seems that if I remove the value for StdOut, it doesn't work again.

Now there you go... enjoy yourself :)


DragonSlayer.
PS: Wow, that's a bargain for 50pts :p  ... but I sort of like took it as a personal challenge, heh

 

by: swift99Posted on 2003-07-18 at 06:03:47ID: 8951377

I also achieved a similar solution at about 1:00 AM.  My clue was that I went home where I run Win98,which doesn't support named pipes, so I used anonymous pipes instead.  When you create an anonymous pipe, both the read and write handle are returned.  I passed the write handle to CreateProcess, and opened a streeam on the read handle, and voila!

The actual solution was the sort I expected (duh - you need separate input and and output handles), but it was a sure challenge to sort it out.

Points increased to 150 ... thanks for the assist!

 

by: DragonSlayerPosted on 2003-07-18 at 07:21:12ID: 8952049

thanks for the points :)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...