2011-04-25 36 views
0

基本上我想在使用popen運行程序時讀取標準輸出中的所有數據。然而,我運行的程序不會返回最後一個輸出行到我的緩衝區,我不明白爲什麼(我的理解:我會得到任何輸出發送到stdout {unbuffered?}從popen)。C++ popen沒有得到所有標準輸出

// $Id: popen.cpp 126 2011-04-25 18:48:02Z wus $ 

#include <iostream> 
#include <stdio.h> 

using namespace std; 

/** 
* run debians apt-get and check output 
*/ 
int main(int argc, char **argv, char **envp) { 

    FILE *fp; 
    char buffer[9]; 
    // select a package which is not installed and has uninstalled dependencies, 
    // apt-get will ask if it should installed «Y» or nor «n». 
    char command[255] = "apt-get install python-wxtools"; 
    cout << command << endl; 

    // Execute command, open /dev/stdout for reading 
    fp = popen(command, "r"); 

    // read output character by character 
    while (fread(buffer, 1, 1, fp) != EOF) { 
     cout << buffer; 
    } 

    // close 
    pclose(fp); 
} 

原生輸出看起來是這樣的:

$ sudo apt-get install python-wxtools 
Reading package lists... Done 
Building dependency tree  
Reading state information... Done 
The following extra packages will be installed: 
    python-wxgtk2.8 python-wxversion 
Suggested packages: 
    wx2.8-doc wx2.8-examples ruby wish tk8.5 tcsh csh octave3.0 mksh pdksh 
    python-xml editra 
The following NEW packages will be installed: 
    python-wxgtk2.8 python-wxtools python-wxversion 
0 upgraded, 3 newly installed, 0 to remove and 8 not upgraded. 
Need to get 5,942kB of archives. 
After this operation, 25.0MB of additional disk space will be used. 
Do you want to continue [Y/n]? 

注意:只有一行在最後一行的末尾。

當我用我自己的程序

,最後一行缺少(輸出)

$ sudo ./test/popen 
g++ -Wall -o test/popen test/popen.cpp 
test/popen.cpp: In function ‘int main(int, char**, char**)’: 
test/popen.cpp:22: warning: comparison between signed and unsigned integer expressions 
apt-get install python-wxtools 
Reading package lists... 
Building dependency tree... 
Reading state information... 
The following extra packages will be installed: 
    python-wxgtk2.8 python-wxversion 
Suggested packages: 
    wx2.8-doc wx2.8-examples ruby wish tk8.5 tcsh csh octave3.0 mksh pdksh 
    python-xml editra 
The following NEW packages will be installed: 
    python-wxgtk2.8 python-wxtools python-wxversion 
0 upgraded, 3 newly installed, 0 to remove and 8 not upgraded. 
Need to get 5,942kB of archives. 
After this operation, 25.0MB of additional disk space will be used. 

注:換行,在輸出的結尾,當它到達文件末尾

回答

1

問題不是你沒有閱讀最後一行,問題是你沒有顯示它,因爲cout被行緩衝。

cout << buffer << flush; 

應該工作。

+0

這很有趣。如果我使用它,我的控制檯似乎在程序結束時掛起。 – Spliffster 2011-04-25 20:28:37

+0

奇怪。不在這裏。你使用哪種終端模擬器? – AProgrammer 2011-04-26 05:58:17

4

的fread不返回EOF。相反,它返回0.但我懷疑問題是apt-get檢測到它的輸入不是tty,因此根本不打印提示。

+0

而且不能保證它所讀取的內容是以空字符結尾的,所以通過'<<'運算符輸出最多是可疑的。 – 2011-04-25 19:54:06

+0

我應該使用哪個函數來讀取,直到輸入流結束? – Spliffster 2011-04-25 19:55:17

+0

+1表示fread問題。對於顯示問題的來源,請參閱我的答案。 – AProgrammer 2011-04-25 19:58:41