[英]How can I execute external commands in C++/Linux?
I just want to know which is the best way to execute an external command in C++ and how can I grab the output if there is any?我只想知道在 C++ 中执行外部命令的最佳方法是什么,如果有的话,我该如何获取 output?
Edit : I Guess I had to tell that I'm a newbie here in this world, so I think I'm gonna need a working example.编辑:我想我不得不告诉我我是这个世界上的新手,所以我想我需要一个可行的例子。 For example I want to execute a command like:例如,我想执行如下命令:
ls -la
how do I do that?我怎么做?
An example:一个例子:
#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
definitely does the job that you're looking for, but it has a few drawbacks: popen
绝对可以完成您正在寻找的工作,但它有一些缺点:
If you want invoke a subprocess and provide input and capture output then you'll have to do something like this:如果您想调用子流程并提供输入并捕获 output 那么您必须执行以下操作:
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 );
}
Of course, you can replace the execlp
with any of the other exec functions as appropriate.当然,您可以根据需要将execlp
替换为任何其他 exec 函数。
use system("ls -la") function使用系统(“ls -la”)function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.