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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/671461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:38:03  来源:igfitidea点击:

How can I execute external commands in C++/Linux?

c++linuxcommand-line

提问by Lipis

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++ 中执行外部命令的最佳方式,以及如何获取输出(如果有)?

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?

我怎么做?

回答by Mehrdad Afshari

Use the popenfunction.

使用该popen功能。

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);

回答by Mehrdad Afshari

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 );
}

回答by Peter Kovacs

popendefinitely 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)
  • It only works in one direction, either you can provide input to the subprocess or you can read its output.
  • 它在您正在执行的命令上调用一个 shell(这意味着您需要清除任何用户提供的命令字符串)
  • 它只在一个方向上起作用,您可以向子流程提供输入,也可以读取其输出。

If you want invoke a subprocess and provide input and capture output then you'll have to do something like this:

如果要调用子流程并提供输入和捕获输出,则必须执行以下操作:

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 execlpwith any of the other exec functions as appropriate.

当然,您可以根据需要将 替换为execlp任何其他 exec 函数。