禁止输出到cout从链接库 [英] Suppress output to cout from linked library

查看:205
本文介绍了禁止输出到cout从链接库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要链接我的C + +程序对一些共享库生成方式太多输出到 std :: cout std :: cerr 使它们对我的用途都无用。我可以访问这些库的C ++源代码,但不能修改它们。



有一种方法可以重定向他们的输出到不同的流或压缩它时链接我的代码?我宁愿在C + +中的一种干净的方式,但担心这将是不可能的我也会很高兴与脏链接器黑客。还有一个代理 libstdc ++ 将是最后的手段。



我使用GNU工具链在Linux下的 g ++ libtool ld p>

解决方案

好的没有人似乎打了它,这是我的链接器建议:


  1. 插入libc,提供您自己的 write(),并过滤输出到文件描述符 1 2

  2. 将您自己的代码静态链接到libc,然后将共享版本插入到静默
  3. 插入libc,提供 my_write()函数, code> write()使用 dlsym()
  4. > write 时,通过传递 -Wl, - wrap = write 链接共享库。然后在一个名为 __ wrap_write 的函数中将任何输出静态到文件描述符 1 2 c $ c>。其他文件描述符应调用 __ real_write

不知道,文件描述符 1 2 对应于 stdout stderr ,它们最终写入 cout / cerr 写的 cout 调用 fwrite 具有不同级别的缓冲和不同级别的shenanigans。



最好的选择是选项4,缺点是你必须调整共享库的最终链接。 p>

接下来最好的是上面的选项2,缺点是你的最终可执行文件更大,但不必在你自己的代码中使用傻的函数。



链接



插入





包装




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.

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.

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:

  1. Interpose libc, provide your own write(), and filter output to file descriptors 1 and 2.
  2. Statically link your own code against libc, and then interpose the shared version to squelch write() as above.
  3. Interpose libc, providing a my_write() function that bypasses write() using dlsym().
  4. Wrap write when linking the shared libraries by passing -Wl,--wrap=write. Then squelch any output to file descriptors 1 and 2 in a function called __wrap_write. Other file descriptors should call through to __real_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.

Your best bet is option 4, the downside is you must tweak the final link for the shared libraries.

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.

Links

Interposing

Wrapping

这篇关于禁止输出到cout从链接库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆