问题
I have a WIN 32 console Application which uses functionality from a 3rd party dll for which I don't have the source code. When calling an exported function from this particular dll, my Console is filled with messages originating from the exported method.
Is there any way to disable the console output "localized" for the 3rd party dll? Of course the Original dll "loader" process (My application) must still be able to provide console output since it's being called as a sub-process by a client scripting toolkit that needs to interpret the console. So you can imagine that if I pass Uncontrolled console output to this Parent Process things can go wrong.
I've tried the answer from this post:
Disable Console Output from External Program (C++)
like this:
system( "3rdparty.dll >nul 2>nul" )
;
but it does nothing.
回答1:
You can redirect stdout
and stderr
to a file before you call into the 3rd-party library and then redirect them back afterwards.
You can write a class like this: (this is for Windows and Visual C++. Other more POSIX-like environments need slightly different code.)
class RedirectStandardOutputs {
private:
int m_old_stdout, m_old_stderr;
public:
RedirectStandardOutputs (char const * stdout_name, char const * stderr_name)
: m_old_stdout (-1), m_old_stderr (-1)
{
fflush (stdout);
fflush (stderr);
m_old_stdout = _dup(_fileno(stdout));
m_old_stderr = _dup(_fileno(stderr));
freopen (stdout_name, "wb", stdout);
freopen (stderr_name, "wb", stderr);
}
~RedirectStandardOutputs ()
{
fflush (stdout);
fflush (stderr);
_dup2 (m_old_stdout, _fileno(stdout));
_dup2 (m_old_stderr, _fileno(stderr));
}
};
Also remember that you'll need to include both <stdio.h>
and <io.h>
.
The above class redirects both stdout
and stderr
to ordinary files in its constructor, and restores them in its destructor. You can use it like this:
// This function writes stuff to the console:
void Foo (int i)
{
printf ("(%d) Hello, world!\n", i);
fprintf (stderr, "(%d) Hello, again.\n", i);
}
// ...
// Later, you call the Foo() function three times, but only the
// second one is redirected:
Foo (0);
{
RedirectStandardOutputs rso ("x.txt", "y.txt");
Foo (1);
}
Foo (2);
Note that this is probably not very fast (specially on Windows,) so keep it out of performance-sensitive areas.
If you want to disable writing to console instead of just redirecting them to a text file, you still can use this approach, but you have to pass in the string "NUL"
for the file name, i.e.:
RedirectStandardOutputs rso ("NUL", "NUL");
Hope this helps.
来源:https://stackoverflow.com/questions/31891584/temporarly-disabling-console-output-from-a-3rd-party-dll