写入终端,尽管通过 bash 中的管道重定向

writing to terminal despite redirection by a pipe in bash

本文关键字:bash 管道 重定向 终端      更新时间:2023-10-16

我希望仍然能够以C++写入终端(以显示进度报告(,即使我的程序被用户使用 bash 中的管道重定向,例如使用命令:

myprogram | sort

有没有办法?

您不能也不应该尝试控制用户希望如何处理程序的输出。您应该努力以最好的意图使用标准流。

  1. 将信息性消息写入std::cout/stdout
  2. 将错误/警告消息写入std::cerr/stderr

如果用户希望看到程序的输出,同时仍然能够将输出保存到文件中,则可以使用 tee

program | tee filename

我找到了答案。

int fd = open(ctermid(NULL), O_WRONLY);
std::string text("hello my terminal!);
write(fd, text.c_str(), text.size());
close(fd);
即使标准,标准输出

和标准被重定向,这也非常有效!