2017-08-17 31 views
0

我有兩個進程:​​和t2.cpp管道命令使標準輸入中斷

​​和t2.cpp被簡化了,我想很容易地描述這個問題。

//t1.cpp 
#include <iostream> 
using namespace std; 
int main() 
{ 
    cout << "hello\n" 
     << "world\n" 
     << "ok ok\n"; 
    return 0; 
} 

//t2.cpp 
#include <iostream> 
#include <limits> 
using namespace std; 
int main()                                                  
{ 
    string str; 
    while(getline(cin,str)){ 
     cout << str <<endl; 
    } 

    //cin.clear(); 
    //flush the cin 
    //cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); 

    char x; 
    cin >> x; 
    return 0; 
} 

編譯​​和t2.cpp後。我以這種方式執行它們./t1 | ./t2

發生問題! cin >> x; in t2.cpp失敗!我沒有機會從鍵盤上打字。

看起來pipe命令實現了redirecting the STDIN_FILENO。它是否同時禁止標準輸入?

我的苛刻要求,是從t1的輸出與shell命令|獲取數據,此外,我想與用戶交互t2。例如,我將顯示Sure to del?[y/n],and wait users's anwser.

+2

不是真正的C++問題。 https://unix.stackexchange.com/questions/103885/piping-data-to-a-processs-stdin-without-causing-eof-afterward – LogicStuff

+0

我認爲正確的答案是「do 「,但我不知道那是什麼。它是從'/ dev/tty'讀取的嗎?那麼,我怎麼能可靠地發送輸入到我管道'less'的任何命令呢? –

回答

0

最後,我們在處理使用「的/ dev/tty的」這個問題

FILE *file = fopen("/dev/tty","r"); 
if(NULL == file){ 
    /*error*/ 
} 
int ch = fgetc(file); 
if('y' == ch || 'Y' == ch){ 
    /*balabala*/ 
} 

stdinstdout被重定向,我們也可以讀或寫FR om /dev/tty

0

其實,有什麼可以做在C++代碼中。 t1必須從標準輸入讀取並將其回送到標準輸出,該標準被重定向。你可以在不同的地方做這樣的事情:

T value; 
std::cin >> value; 
std::cout << value; 

或者模擬shell命令的行爲的意見(附加標準輸入後t1寫完它的數據到標準輸出):

std::copy(std::istreambuf_iterator<char>(std::cin), 
      std::istreambuf_iterator<char>(), 
      std::ostreambuf_iterator<char>(std::cout)); 
+1

這可以工作,但不是最好的解決方案,因爲它混合了兩個輸入源;你不能說出來自't1'和來自用戶的信息。另外,如果你輸入't1',你又會失去用戶輸入。 –

相關問題