Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get already running windows process' console output in a command prompt? Direct StreamReader to command prompt

I am trying to determine if there is a way to get the console output, in a command prompt, of an already running process in the windows environment via C#. I have seen an answer for linux based systems through the shell and also a way to retrieve a Process object. Though neither offer a solution to get the output of the process.

I my code I currently find a process (MongodDB daemon) this way

Process[] procs = Process.GetProcessesByName("mongod");
if (procs.Length > 0)
{
    MongoProcess = procs[0];
    Console.Out.WriteLine("Found mongod.exe, process id: " + MongoProcess.Id);
}

I have also found the Process.StandardOutput property which supplies "A StreamReader that can be used to read the standard output stream of the application.". Is there a way to direct this StreamReader input to a command prompt output?

I also know that I can start a process and display the command prompt (process output), but this is only when the process is started "by me".

Process.Start(new ProcessStartInfo("notepad.exe") { CreateNoWindow = false })

I also know that I could simply read from the StreamReader and display the output in my own way, but I would really prefer to just display a command prompt.

like image 329
KDecker Avatar asked Mar 30 '16 19:03

KDecker


1 Answers

Windows does not provide any mechanism to retroactively give another process a standard output handle if it was created without one. (Besides, in most cases an application will check the standard output handle only during startup.)

If you know (or can successfully guess) how a specific application generates output, it may in principle be possible to start capturing that output by injecting your own code into the process. For example, if you know that the application uses C++ and is dynamically linked to the VS2015 runtime library, you might inject code that calls freopen as shown here. (In this scenario, you must know which runtime library the application uses because you have specify it when looking up the address for freopen.)

However, code injection is not trivial, and creates a risk of inadvertently causing the process to malfunction. Also, any output that has already been generated will almost certainly have been discarded and be irrevocably lost.

like image 193
Harry Johnston Avatar answered Oct 07 '22 00:10

Harry Johnston