diff --git a/src/engine/helper/HL_Process.cpp b/src/engine/helper/HL_Process.cpp index ca82d43c..9d0de366 100644 --- a/src/engine/helper/HL_Process.cpp +++ b/src/engine/helper/HL_Process.cpp @@ -1,5 +1,6 @@ #include "HL_Process.h" - +#include +#include #ifdef TARGET_WIN # define popen _popen @@ -98,4 +99,35 @@ std::string OsProcess::execCommand(const std::string& cmd) } return result; } + +void OsProcess::asyncExecCommand(const std::string& cmdline, + std::function callback, + bool& finish_flag) +{ + std::thread t([cmdline, callback, &finish_flag]() + { + std::string cp = cmdline; + std::shared_ptr pipe(popen(cp.c_str(), "r"), pclose); + if (!pipe) + throw std::runtime_error("Failed to run."); + + char buffer[1024]; + std::string result = ""; + while (!feof(pipe.get()) && !finish_flag) + { + if (fgets(buffer, 1024, pipe.get()) != nullptr) + { + if (callback) + callback(buffer); + result += buffer; + } + } + + finish_flag = true; + }); + + while (!finish_flag) + std::this_thread::sleep_for(std::chrono::milliseconds(1)); +} + #endif diff --git a/src/engine/helper/HL_Process.h b/src/engine/helper/HL_Process.h index 3c1de6a4..52347aa7 100644 --- a/src/engine/helper/HL_Process.h +++ b/src/engine/helper/HL_Process.h @@ -2,11 +2,16 @@ #define __HL_PROCESS_H #include +#include class OsProcess { public: static std::string execCommand(const std::string& cmdline); + static void asyncExecCommand(const std::string& cmdline, + std::function callback, + bool& finish_flag); + }; #endif