问题
What is a simple, elegant, and effective cross-platform way to execute an external program in C++ and get the return code from it?
int execute(std::string const &path, std::vector<std::string> const &arguments = {})
{
//...
}
Since we're waiting for the called program to finish before continuing execution, the called program should use our program's input/output/error streams. If, for any number of reasons, path
isn't executable, just throw an exception (e.g. std::invalid_argument
).
Obviously, don't use system()
.
回答1:
If it is just one single program you need to execute, spawn a worker thread and have that thread call system
:
void executeProgram(std::string programName) {
system(programName.c_str());
}
void execute() {
string programName = "test.cpp";
std::thread worker (executeProgram, programName);
worker.join(); //wait for the worker to complete
}
If you need to be able to spawn many programs, a thread pool class to delegate worker threads and join them upon completion might make more sense.
回答2:
At least for command-line applications, I solved this issue using popen
.On windows is _popen
but that is easily solved with a define
来源:https://stackoverflow.com/questions/29001583/simple-c-cross-platform-way-to-execute-an-external-program