简体   繁体   English

如何在 C++/Linux 中执行外部命令?

[英]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?我怎么做?

Use the popen function.使用popen function。

Example (not complete, production quality code, no error handling):示例(不完整,生产质量代码,无错误处理):

FILE* file = popen("ls", "r");
// use fscanf to read:
char buffer[100];
fscanf(file, "%100s", buffer);
pclose(file);

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绝对可以完成您正在寻找的工作,但它有一些缺点:

  • It invokes a shell on the command you're executing (which means that you need to untaint any user provided command strings)它在您正在执行的命令上调用 shell(这意味着您需要清除任何用户提供的命令字符串)
  • It only works in one direction, either you can provide input to the subprocess or you can read its output.它只在一个方向上起作用,您可以为子进程提供输入,也可以读取它的 output。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM