问题描述
我需要将我的 C++ 程序与几个共享库链接起来,这些共享库生成太多的输出到 std::cout
和 std::cerr
使它们都无用我的用途.我可以访问这些库的 C++ 源代码,但不能修改它们.
I need to link my C++ programs against a couple shared libraries which generate way too much output to std::cout
and std::cerr
rendering them both useless for my uses. I have access to the C++ source code of these libraries, but cannot modify them.
有没有办法将它们的输出重定向到不同的流或在链接到我的代码时抑制它?我更喜欢 C++ 中的一种干净的方式,但担心那是不可能的,我也会对肮脏的链接器黑客感到满意.作为最后的手段,代理 libstdc++
"也可以.
Is there a way to redirect their output to a different stream or suppress it when linked against my code? I would prefer a clean way in C++, but fearing that that would be impossible I will also be happy with dirty linker hacks. Also a "proxy libstdc++
" would be fine as a last resort.
我正在使用 Linux 下的 GNU 工具链(g++
、libtool
、ld
).
I am working with a GNU toolchain (g++
, libtool
, ld
) under Linux.
推荐答案
好吧,似乎没人注意到它,这是我的链接器建议:
Well nobody seems to have hit on it, here's my linker suggestions:
- 插入 libc,提供自己的
write()
,并将输出过滤到文件描述符1
和2
. - 将自己的代码静态链接到 libc,然后插入共享版本以静噪
write()
如上所述. - 插入 libc,提供一个
my_write()
函数,该函数使用dlsym()
绕过write()
. - 在通过传递
-Wl,--wrap=write
链接共享库时包装write
.然后在名为__wrap_write
的函数中将任何输出抑制到文件描述符1
和2
.其他文件描述符应该调用__real_write
.
- Interpose libc, provide your own
write()
, and filter output to file descriptors1
and2
. - Statically link your own code against libc, and then interpose the shared version to squelch
write()
as above. - Interpose libc, providing a
my_write()
function that bypasseswrite()
usingdlsym()
. - Wrap
write
when linking the shared libraries by passing-Wl,--wrap=write
. Then squelch any output to file descriptors1
and2
in a function called__wrap_write
. Other file descriptors should call through to__real_write
.
请注意,对于那些不知道的人,文件描述符 1
和 2
对应于 stdout
和 stderr
,最终写入 cout
/cerr
机器.这通常是通过 cout
调用 fwrite
来实现的,fwrite
又调用 write
,在不同的级别有不同级别的缓冲和恶作剧.
Note that for those that aren't aware, file descriptors 1
and 2
correspond to stdout
and stderr
, which are eventually written to in the cout
/cerr
machinery. Often this is implemented cout
calls fwrite
which calls write
, with varying levels of buffering and shenanigans at the different levels.
您最好的选择是选项 4,缺点是您必须调整共享库的最终链接.
Your best bet is option 4, the downside is you must tweak the final link for the shared libraries.
其次最好的是上面的选项 2,缺点是您的最终可执行文件要大得多,但不必在自己的代码中使用愚蠢的函数.
Next best is option 2 above, the downside is your final executable is much bigger, but don't have to use silly functions in your own code.
插入
- http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html
- http://www.jayconrod.com/cgi/view_post.py?23
- http://dictionary.die.net/interposing
- http://developers.sun.com/solaris/articles/lib_interposers.html
包装
- http://www.jayconrod.com/cgi/view_post.py?23
- http://okmij.org/ftp/syscall-interpose.html
- 没有 dlsym 的 Linux 中的函数插入
- http://sourceware.org/ml/binutils/2000-09/msg00083.html
这篇关于禁止从链接库输出到 cout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!