0

基本上我想在运行带有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.

注意:输出末尾的换行符

4

2 回答 2

4

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

于 2011-04-25T19:51:17.043 回答
1

问题不在于您没有阅读最后一行,问题是由于 cout 被行缓冲,您没有显示它。

cout << buffer << flush;

应该管用。

于 2011-04-25T19:56:59.137 回答