【发布时间】:2009-03-22 19:10:00
【问题描述】:
我只想知道在 C++ 中执行外部命令的最佳方法是什么,如果有输出,我该如何获取?
编辑:我想我不得不说我是这个世界上的新手,所以我想我需要一个可行的例子。例如我想执行如下命令:
ls -la
我该怎么做?
【问题讨论】:
标签: c++ linux command-line
我只想知道在 C++ 中执行外部命令的最佳方法是什么,如果有输出,我该如何获取?
编辑:我想我不得不说我是这个世界上的新手,所以我想我需要一个可行的例子。例如我想执行如下命令:
ls -la
我该怎么做?
【问题讨论】:
标签: c++ linux command-line
使用popen 函数。
示例(不完整,生产质量代码,无错误处理):
FILE* file = popen("ls", "r");
// use fscanf to read:
char buffer[100];
fscanf(file, "%100s", buffer);
pclose(file);
【讨论】:
一个例子:
#include <stdio.h>
int main() {
FILE * f = popen( "ls -al", "r" );
if ( f == 0 ) {
fprintf( stderr, "Could not execute\n" );
return 1;
}
const int BUFSIZE = 1000;
char buf[ BUFSIZE ];
while( fgets( buf, BUFSIZE, f ) ) {
fprintf( stdout, "%s", buf );
}
pclose( f );
}
【讨论】:
popen 绝对可以满足您的需求,但它有一些缺点:
如果您想调用子流程并提供输入和捕获输出,那么您必须执行以下操作:
int Input[2], Output[2];
pipe( Input );
pipe( Output );
if( fork() )
{
// We're in the parent here.
// Close the reading end of the input pipe.
close( Input[ 0 ] );
// Close the writing end of the output pipe
close( Output[ 1 ] );
// Here we can interact with the subprocess. Write to the subprocesses stdin via Input[ 1 ], and read from the subprocesses stdout via Output[ 0 ].
...
}
else
{ // We're in the child here.
close( Input[ 1 ] );
dup2( Input[ 0 ], STDIN_FILENO );
close( Output[ 0 ] );
dup2( Output[ 1 ], STDOUT_FILENO );
execlp( "ls", "-la", NULL );
}
当然,您可以根据需要将execlp 替换为任何其他 exec 函数。
【讨论】: