A customer wanted to know if they could read the standard output of an already-running process. They didn’t explain why, but my guess is that their main process launches a helper process (not written by them) to begin some workflow, and eventually that helper process launches a console process, which produces the desired output. But they want their main process to read that output, presumably so they can continue automating the workflow.
Unfortunately, there is no way to read the standard output of an already-running process. Standard handles, like the environment variables and current directory, are properties of the process that are not exposed to outsiders by the system.¹
In particular, programs do not expect these properties to change asynchronously. For example, a program that might check the standard output handle and put up a progress spinner if it is a console but not if it is a pipe or file.
Some programs check whether their standard output handle refers to a console (in which case they will use functions like WriteConsoleW to get Unicode support or SetÂConsoleÂTextÂAttribute to get colors. Furthermore, the C runtime libraries typically check their standard output handle at startup to see whether it has been redirected to a file. This alters the behavior of standard I/O functions because buffering is enabled for non-interactive standard output. If you could change the standard output handle out from under a program’s nose, it would try using WriteÂConsoleW to write to something that isn’t a console any more. The calls would fail, and the program would generate no output at all.
It’s actually worse because it’s not uncommon for programs to call GetÂStdÂHandle and save the value in a variable, then use that variable to write to standard output instead of calling GetÂStdÂHandle every time. So even if you managed to change the standard output handle, you’d be too late.
What you have to do is find a way to influence the standard output of the console process at the point it is created. Since the presumed intention is for the output of the child process to be visible to the user, the console process probably inherits its standard output from its parent, so you can get the child to operate with redirected output by redirecting the output of the parent process. You’ll have to figure out how to distinguish the output of the parent from the output of the child, but so too did human beings who ran the helper process manually, so presumably there’s some consistent way of recognizing it.
¹ Of course, that doesn’t stop a program from explicitly exposing a custom mechanism for allowing other processes to manipulate them.
0 comments
Be the first to start the discussion.