- async execute command

This commit is contained in:
Dmytro Bogovych 2018-09-28 20:33:44 +03:00
parent 4da6c88f02
commit 96c2ed3d94
2 changed files with 38 additions and 1 deletions

View File

@ -1,5 +1,6 @@
#include "HL_Process.h" #include "HL_Process.h"
#include <thread>
#include <memory>
#ifdef TARGET_WIN #ifdef TARGET_WIN
# define popen _popen # define popen _popen
@ -98,4 +99,35 @@ std::string OsProcess::execCommand(const std::string& cmd)
} }
return result; return result;
} }
void OsProcess::asyncExecCommand(const std::string& cmdline,
std::function<void(const std::string& line)> callback,
bool& finish_flag)
{
std::thread t([cmdline, callback, &finish_flag]()
{
std::string cp = cmdline;
std::shared_ptr<FILE> 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 #endif

View File

@ -2,11 +2,16 @@
#define __HL_PROCESS_H #define __HL_PROCESS_H
#include <string> #include <string>
#include <functional>
class OsProcess class OsProcess
{ {
public: public:
static std::string execCommand(const std::string& cmdline); static std::string execCommand(const std::string& cmdline);
static void asyncExecCommand(const std::string& cmdline,
std::function<void(const std::string& line)> callback,
bool& finish_flag);
}; };
#endif #endif