简体   繁体   English

在Linux下执行外部命令并等待其完成

[英]Execute external command and wait for it to finish under Linux

Easy question: what is the easiest way to execute an external program (with parameters) from C++ (using g++ and Linux)? 一个简单的问题:从C ++(使用g ++和Linux)执行外部程序(带有参数)的最简单方法是什么? Is there an easier way rather than doing fork/exec and waiting? 有没有比执行fork / exec和等待更简单的方法? I just need to execute the command and wait for it to finish. 我只需要执行命令并等待它完成即可。

Kind of depends on how much you want to interact with the program. 种类取决于您要与程序进行多少交互。

If not at all, you can easily just use system("...."); 如果根本没有,您可以轻松地使用system("....");

If you want some I/O then you can use popen(); 如果需要一些I / O,则可以使用popen();

And if even that is not enough, you will end up will fork() , exec() , wait() , dup() and other functions from this family. 而且,即使这还不够,您最终将得到该系列的fork()exec()wait()dup()和其他函数。

The system() function: system()函数:

#include 

int main (void)
{
        system("ls /home");
        return 0;
}

I have learnt to use screen command a lot, especially for long running scripts. 我学会了很多使用屏幕命令的方法,尤其是对于长时间运行的脚本。 It may be bit of an overkill for you, but it should definitely do the job in this case. 对于您来说,这可能有点过大,但是在这种情况下,它肯定可以胜任。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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