简体   繁体   中英

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:

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 .
  2. Write error/warning messages to 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 .

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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