Frederick Gotham
unread,May 8, 2021, 4:25:57 PM5/8/21You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to
I'm writing a program that links with a handful of shared libraries.
Some of the shared libraries write the occassional infrequent message to
stdout.
I want to suppress the messages outputted from these shared libraries,
namely from statements such as the following:
cout << "whatever" << some_number << endl;
printf("whatever%i\n", some_number);
However I want my own program to still be able to use "cout" to print to
stdout. (I don't have any use for "printf" or any related C-style IO
functions in my pgrogram).
So the first thing I've done is allocated static duration memory for an
'ostream' object. My object is called "g_exclusive_cout":
std::aligned_union<0, std::ostream>::type g_exclusive_cout;
My program is for Linux and so I've started by coding a Linux-specific
solution, however I'm curious as to whether there's a C++11 ANSI/ISO
portable solution.
Next I call the following function when the program starts:
void Suppress_Cout_From_Shared_Libraries(void)
{
fflush(stdout);
static __gnu_cxx::stdio_filebuf<char>
filebuf(dup(fileno(stdout)), std::ios::out);
freopen("/dev/null", "w", stdout);
::new(&g_exclusive_cout) std::ostream(&filebuf);
}
And then lastly I have a macro for exclusive cout, "excout":
#define excout ( \
*static_cast<std::ostream*>( \
static_cast<void*>(&g_exclusive_cout) \
) \
)
And so then in my own program, I always use "excout" instead of "cout",
for example:
int main(void)
{
Suppress_Cout_From_Shared_Libraries();
excout << "Hello World!" << endl;
}
This solution works for me. Of course I've used POSIX-specific functions
and GNU compiler extensions to pull it off. I wonder if there's an
ANSI/ISO C++11 way of doing it? By the way, since multithreading was
introduced into C++11, there is a gaurantee that calls to "cout <<
whatever" are thread-safe. I wonder if my own code with "excout" is
thread-safe, or whether I'll have to wrap methods called on "excout"
within a mutex?