1

How can i read the output of a running console process ? i found a snippet that shows how to do it for a starting process by using ReadFile() on the process handle obtained by CreateProcess(), but my question is, how can i achieve this for a running process ? thanks.

What I have tried is, using OpenProcess() on the Console app (i hardcoded the pid just to test) and then i used ReadFile() on it, but i get gibbrish letters or not showing me anything at all.

Edit: Here's the code i tried, PID is hardcoded just for test.

procedure TForm1.Button1Click(Sender: TObject);
var
  hConsoleProcess: THandle;
  Buffer: Array[0..512] of ansichar;
  MyBuf: Array[0..512] of ansichar;
  bytesReaded: DWORD;
begin
  hConsoleProcess := OpenProcess(PROCESS_ALL_ACCESS, False, 6956);
  ReadFile(hConsoleProcess, Buffer, sizeof(Buffer), bytesReaded, nil);
  OemToCharA(Buffer, MyBuf);
  showmessage(string(MyBuf));

// ShellExecute(Handle, 'open', 'cmd.exe', '/k ipconfig', nil, SW_SHOWNORMAL);
end;
  • Regarding the code in your question, there is no error checking. You simply have to get into the habit of checking return values for errors. – David Heffernan Oct 01 '15 at 14:22

1 Answers1

1

It's unrealistic to expect to be able to do this. Perhaps it possible to hack it, but no good will come of doing so. You could inject into the process, obtain its standard output handle with GetStdHandle. And read from that. But no good will come of that, as I said.

Why will no good come of this? Well, standard input/output is designed for a single reader, and a single writer. If you have two readers, then one, or both, of the readers are going to miss some of the text. In fact I'd be surprised if two blocking synchronous calls to ReadFile were allowed by the system. I'd expect the second one to fail. [Rob's comment explains that this is allowed, but it's more like first come, first served.]

What you could perhaps do is to create a multi-casting program to listen to the output of the main program. Pipe the output of the main program into the multi-caster. Have the multi-caster echo to its standard output and to one or more other pipes.

The bottom line here is that whatever your actual problem is, hooking up multiple readers to the standard out is not the solution.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 1
    In my experience, multiple readers of a single handle tend to *alternate*. I've seen this when a non-console process attaches to the command prompt that started it. First the command prompt reads from stdin, then the other process reads a line of input, then the command prompt again, and so on. It's probably not alternating so much as it is simple first come, first served. So, like you said, nothing good. – Rob Kennedy Oct 01 '15 at 14:26