- fixes & improvements to helper libraries

This commit is contained in:
dmytro.bogovych 2019-01-31 10:11:16 +03:00
parent e83f717076
commit 694ced4d25
4 changed files with 37 additions and 3 deletions

View File

@ -218,6 +218,7 @@ std::string OsProcess::execCommand(const std::string& cmd)
#include <unistd.h>
#include <vector>
#include "helper/HL_String.h"
#include "helper/HL_Sync.h"
std::shared_ptr<std::thread> OsProcess::asyncExecCommand(const std::string& cmdline,
std::function<void(const std::string& line)> line_callback,
@ -226,6 +227,7 @@ std::shared_ptr<std::thread> OsProcess::asyncExecCommand(const std::string& cmdl
{
std::shared_ptr<std::thread> t = std::make_shared<std::thread>([cmdline, line_callback, finished_callback, &finish_flag]()
{
ThreadHelper::setName("OsProcess::asyncExecCommand");
std::string cp = cmdline;
FILE* pipe = popen(cp.c_str(), "r");
if (!pipe)
@ -258,7 +260,7 @@ std::shared_ptr<std::thread> OsProcess::asyncExecCommand(const std::string& cmdl
int r;
do
{
r = (int)read(fno, buffer, sizeof(buffer) - 1);
r = static_cast<int>(read(fno, buffer, sizeof(buffer) - 1));
if (r > 0)
{
buffer[r] = 0;
@ -285,6 +287,10 @@ std::shared_ptr<std::thread> OsProcess::asyncExecCommand(const std::string& cmdl
}
}
if (finish_flag)
{
// Send SIGINT to process
}
if (pipe)
pclose(pipe);
@ -296,4 +302,26 @@ std::shared_ptr<std::thread> OsProcess::asyncExecCommand(const std::string& cmdl
return t;
}
pid_t OsProcess::findPid(const std::string& cmdline)
{
try
{
std::ostringstream oss;
oss << "pgrep -f " << "\"" << cmdline << "\"";
std::string output = execCommand(oss.str());
return std::atoi(output.c_str());
}
catch(...)
{
return 0;
}
}
void OsProcess::killByPid(pid_t pid)
{
if (pid <= 0)
return;
execCommand("kill -9 " + std::to_string(pid));
}
#endif

View File

@ -14,6 +14,10 @@ public:
std::function<void(const std::string& line)> line_callback,
std::function<void(const std::string& reason)> finished_callback,
bool& finish_flag);
#if defined(TARGET_OSX) || defined(TARGET_LINUX)
static pid_t findPid(const std::string& cmdline);
static void killByPid(pid_t pid);
#endif
};

View File

@ -335,10 +335,11 @@ std::string StringHelper::replace(const std::string& s, char f, char r)
std::string StringHelper::replace(const std::string& s, const std::string& tmpl, const std::string& n)
{
std::string result(s);
std::string::size_type p;
while ( (p = result.find(tmpl)) != std::string::npos)
std::string::size_type p = 0;
while ( (p = result.find(tmpl, p)) != std::string::npos)
{
result.replace(p, tmpl.size(), n);
p += n.size();
}
return result;

View File

@ -268,6 +268,7 @@ size_t TimerQueue::cancelAll() {
void TimerQueue::run()
{
ThreadHelper::setName("TimerQueue");
while (!m_finish)
{
auto end = calcWaitTime();