C ++ popen没有得到所有的stdout

时间:2011-04-25 19:40:09

标签: c++ stdout iostream popen apt-get

基本上我想在使用popen运行程序时从stdout读取所有数据。但是,我运行的程序不会将最后一个输出行返回到我的缓冲区中,我不明白为什么(我的理解:我会从popen将任何输出发送到stdout {unbuffered?})。

// $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.

注意:输出结尾的换行符

2 个答案:

答案 0 :(得分:4)

fread在到达文件末尾时不返回EOF。相反,它返回0.但我怀疑问题是apt-get检测到它的输入不是tty,因此根本不打印提示。

答案 1 :(得分:1)

问题不是你没有读到最后一行,问题是由于cout是行缓冲而你没有显示它。

cout << buffer << flush;

应该有用。