简体   繁体   中英

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)? Is there an easier way rather than doing fork/exec and waiting? 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("....");

If you want some I/O then you can use popen();

And if even that is not enough, you will end up will fork() , exec() , wait() , dup() and other functions from this family.

The system() function:

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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