This is a mirror of official site: http://jasper-net.blogspot.com/

[Windows, C#] Splitting/Forking/Cloning Standard Output

| Wednesday, July 13, 2011
For one of my little projects at work, I’ve been creating a utility which will run as a child process which is just hosted as a console application. It prints a lot of output to console, and it would be kinda useful to be able to capture all the output from the child process, either in a text file, or by reading it in the parent process, or both. I know you can capture child process output in the parent process, or redirect it to a file by passing in a file handle to the CreateProcess API. However, it seems rather a shame to also give up the console window output in the same way…

So here I started wondering – shouldn’t it be possible to keep using Console.WriteLine and have the output appear in multiple places, by using some sort of special splitting or cloning pipe? A little research turned up nothing really explicit on what to do, but a few Windows functions which look they could feature somewhere in a solution:

GetStdHandle, SetStdHandle, CreatePipe, CreateFile.

So where do we get started?
Part 1:  Interception

By reading about SetStdHandle, GetStdHandle, and CreateFile with special “CONIN$” and “CONOUT$” files we can see that there’s a few abstraction layers here.

  1.     Top layer: The console class, which we can call WriteLine on.
  2.     Managed stream wrapper: there are properties on the Console class: Console.In and Console.Out which represent the file streams in managed code
  3.     Underlying window ‘standard input/output’ concepts: Windows tracks ‘standard input’ and ‘standard output’ file streams for a process, which seem like they are either wrapper objects, or logical indexes into a table of file handles.
  4.     Raw file handle: suitable for passing to APIs that know and care about low level file handles, and don’t have concepts like standard input and standard output. APIs like ‘Read’ and ‘Write’ (bytes)

Calling SetStdHandle will let us insert our own file handle underneath the logical ‘standard input/standard output’ layer at the raw file handle layer. But we can only make each concept logically point at a single file handle, so what should we insert in order to have output in two places?

Read more: The Activity Designer
QR: windows-c-splitting-forking-cloning-standard-output.aspx

Posted via email from Jasper-net

0 comments: