基本上我想在使用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.
注:換行,在輸出的結尾,當它到達文件末尾
這很有趣。如果我使用它,我的控制檯似乎在程序結束時掛起。 – Spliffster 2011-04-25 20:28:37
奇怪。不在這裏。你使用哪種終端模擬器? – AProgrammer 2011-04-26 05:58:17