Is it possible to get the output of a program while it's running?

被刻印的时光 ゝ 提交于 2019-12-05 18:18:44

There are some interesting articles in Code Project:

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.

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.

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);

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!