これはばかげた質問のように聞こえるかもしれません。私はC++を初めて使用します。
apt-get install
Debianでは、popenで呼び出そうとします。このプログラムの出力を解析する必要があります。残念ながら、apt-getの完全な出力を読み取ることができません。
ある時点で、apt-getはユーザー入力を要求する場合があります(依存関係をインストールする必要があるかどうかを尋ねます)。私のプログラムはこの行を出力できません。
Whisは最後の行です(以下の例を参照してください。私のプログラムで欠落している行は「[Y / n]を続行しますか?」です)出力されませんか?
apt-getコマンドを手動で実行すると、コンソールの出力は次のようになります。
$ 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.
注:出力の最後の改行
popenのリファレンス実装は、C++では次のようになります。
// $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];
// must use a package which asks for dependencies
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);
}
Linuxシステムでこれを試してみます
$ uname -a
Linux shell1 2.6.35-28-server #50-Ubuntu SMP Fri Mar 18 18:59:25 UTC 2011 x86_64 GNU/Linux
$ gcc --version
gcc (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.