简单的C ++跨平台方式来执行外部程序 [英] Simple C++ cross-platform way to execute an external program
问题描述
在C ++中执行外部程序并从中获取返回代码的简单,优雅,有效的跨平台方法是什么?
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 = {})
{
//...
}
因为我们正在等待被调用程序在继续执行之前,被调用程序应使用我们程序的输入/输出/错误流。如果出于各种原因, path
无法执行,则抛出异常(例如, std :: invalid_argument
)。
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
).
很显然,不要使用 system()
。
推荐答案
如果您只需要执行一个程序,则生成一个工作线程并让该线程调用 system
:
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.
这篇关于简单的C ++跨平台方式来执行外部程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!