【问题标题】:How to temporarily suppress output from printf?如何暂时抑制 printf 的输出?
【发布时间】:2017-10-13 11:17:21
【问题描述】:

在控制台应用程序中,我正在调用一个库函数,该函数输出一些我不感兴趣的消息(可能使用 printf):

void libFoo()
{
    // does some stuff
    printf("boring message");
    // does some more stuff
}

我尝试抑制 cout 之前不起作用,因此我认为 libFoo 正在使用 printf:

cout << "interesting messsage" << endl;
streambuf* orig_buf = cout.rdbuf();
cout.rdbuf(NULL);
libFoo();
cout.rdbuf(orig_buf);
cout << "another interesting messsage" << endl;

此代码输出所有这些消息。有没有办法暂时抑制 printf 的输出?我正在使用 Linux Mint。

【问题讨论】:

  • 你可以,但我认为你不能完全便携。查看 freopen 和 dup 函数。
  • 记住 cout 是缓冲的,而 cerr 不是。如果您禁用某些东西,请确保缓冲区已刷新。
  • 也许你的库正在使用日志功能,而不是专门printf...如果存在这种可能性,请考虑弄清楚如何设置日志级别...
  • “无聊的消息”可能会显示在stderr 而不是stdout
  • 我认为唯一定义的方法是将stdout重定向到其他地方,例如/dev/null,然后再恢复它。

标签: c++ linux


【解决方案1】:

这里是:

int supress_stdout() {
  fflush(stdout);

  int ret = dup(1);
  int nullfd = open("/dev/null", O_WRONLY);
  // check nullfd for error omitted
  dup2(nullfd, 1);
  close(nullfd);

  return ret;
}

void resume_stdout(int fd) {
  fflush(stdout);
  dup2(fd, 1);
  close(fd);
}

如果这是 C++,还要刷新 cout 以进行良好的衡量。

编辑澄清

您传递给resume_stdoutfd 与您收到的supress_stdout 的返回值相同。

【讨论】:

  • 你为参数 fd 传递了什么?
  • @tyebillion,你从suspend_stdout得到的int
  • 是的,这对我有用。我只需要#include 来获得 O_WRONLY 的定义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 2018-08-14
  • 2011-11-11
  • 2014-06-02
  • 1970-01-01
  • 1970-01-01
  • 2016-03-07
相关资源
最近更新 更多