Simple C++ cross-platform way to execute an external program

走远了吗. 提交于 2019-12-07 11:00:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!