views:

160

answers:

5

If I have a windows console program written with c++, is it possible to retrieve that program's standard output, while the program is running? And if not, what would be the best way to rewrite the program? I know I could output to files and continuously check those files for updates. Is there another way? Is there a better way?

+1  A: 

If it is a ready console executable you can allways redirect it output in a file like this:

c:> echo Some text > file

or

c:> program > file

If you mean this? As your question is not exactly clear.

\\ into another program

Oh, Ok
But my first answer is also used to it. As there is also another possibility like:

c:> program1 | program2

its make a "pipe" between console programs
program2 receive on it stdin what program1 throws to stdout
Its common old-aged Unix-way practice in console programs.
And in such way NO need to rewrite programs to specifically support it.

+1  A: 

There are some interesting articles in Code Project:

kgiannakakis
A: 

Yes, if you start the program yourself:

in CreateProcess, you pass a STARTUPINFO where you can specify handles for SDIN, STDOUT and STDERR. Note that oyu need to supply all three once you specify the STARTF_USESTDHANDLES flag.

Also, the handles need to be inheritable (otherwise, the child process can't access them), so the SECURITY_ATTRIBUTES basically need to look at least like this:

SECURITY_ATTRIBUTES secattr = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };

You could open handles to disk files that contain input and receive output. Alternatively, this can be Pipes that can be read / written incrementally while the console app is running.

peterchen
A: 

If you are only interested in the program's stdout, popen() makes this pretty simple:

FILE* program_output = popen("command line to start the other program");
//read from program_output as you would read a "normal" file
//...
pclose(program_output);
Éric Malenfant
A: 

You'd most likely need to use pipes to achieve this, and since you're using Windows, here's a link to MSDN article with an example that seems to do exactly what you wanted.

Dmitry