简体   繁体   English

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

[英]writing to terminal despite redirection by a pipe in bash

I want to still be able to write in C++ to the terminal (to show a progress report) even when my program is redirected using a pipe in bash by the user, like for example with the command: 我希望即使用户使用bash中的管道将程序重定向到我的程序(例如显示以下命令),我也仍然可以用C ++编写到终端(以显示进度报告):

myprogram | sort

Is there a way to this? 有办法吗?

You cannot and should not try to control how the user wants to process the output of your program. 您不能也不应该尝试控制用户如何处理程序输出。 You should strive to use the standard streams with the best of intentions. 您应该尽力使用标准流。

  1. Write informational messages to std::cout / stdout . 将参考消息写入std::cout / stdout
  2. Write error/warning messages to std::cerr / stderr . 将错误/警告消息写入std::cerr / stderr

If the user wishes to see the output of your program while still being able to save the output to a file, they may use tee . 如果用户希望在仍能将输出保存到文件的同时查看程序的输出,则可以使用tee

program | tee filename

I have found an answer. 我找到了答案。

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

This works perfectly even if stdin, stdout and stderr have been redirected! 即使已将stdin,stdout和stderr重定向,这也可以正常工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM