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 に答える