Stack overflow地址:How can I execute external commands in C++/Linux? - Stack Overflow
翻译:
我想要一个最好的方式在C++中执行额外的命令,如果有任何输出的话,我该怎么得到呢?
修改:我猜我不得不说我是这个世界的新人,所以我认为我需要一个工作的例子。比如我想要执行的命令如下所示:
ls -la
我该怎么做?
Answers1:
使用popen函数。
示例(不完全,没有错误处理):
FILE* file = popen("ls", "r");
// use fscanf to read:
char buffer[100];
fscanf(file, "%100s", buffer);
pclose(file);
Answers2:
一个例子:
#include
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 );
}
Answers3:
popen肯定可以做你期望的这个工作,但是这有几个缺点:
1.它在你执行的命令上调用一个shell(这意味着你需要清楚任何用户提供的命令字符串)
2.它只在一个方向上工作,要么你提供子请求的输入,要么你读取它的输出
如果你想要调用一个子请求,提供输入并且获取输出,你可能需要像下面这么做:
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替换为任何其他正确的执行函数。
网友评论