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

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

问题描述

我需要将我的 C++ 程序与几个共享库链接起来,这些共享库生成太多的输出到 std::coutstd::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++libtoolld).

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. 插入 libc,提供自己的 write(),并将输出过滤到文件描述符 12.
  2. 将自己的代码静态链接到 libc,然后插入共享版本以静噪 write() 如上所述.
  3. 插入 libc,提供一个 my_write() 函数,该函数使用 dlsym() 绕过 write().
  4. 在通过传递 -Wl,--wrap=write 链接共享库时包装 write.然后在名为 __wrap_write 的函数中将任何输出抑制到文件描述符 12.其他文件描述符应该调用 __real_write.
  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.

请注意,对于那些不知道的人,文件描述符 12 对应于 stdoutstderr,最终写入 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.

插入

包装

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

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