簡體   English   中英

盡管通過bash中的管道重定向,但仍寫入終端

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

我希望即使用戶使用bash中的管道將程序重定向到我的程序(例如顯示以下命令),我也仍然可以用C ++編寫到終端(以顯示進度報告):

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);

即使已將stdin,stdout和stderr重定向,這也可以正常工作!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM