forked from janhq/cortex.cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_executor.h
More file actions
50 lines (42 loc) · 1.22 KB
/
command_executor.h
File metadata and controls
50 lines (42 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#pragma once
#include <array>
#include <cstdio>
#include <memory>
#include <stdexcept>
#include <string>
#ifdef _WIN32
#define POPEN _popen
#define PCLOSE _pclose
#else
#define POPEN popen
#define PCLOSE pclose
#endif
class CommandExecutor {
public:
CommandExecutor(const std::string& command) {
FILE* pipe = POPEN(command.c_str(), "r");
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
m_pipe = std::unique_ptr<FILE, void (*)(FILE*)>(pipe, [](FILE* file) { if (file) { PCLOSE(file); } });
}
CommandExecutor(const CommandExecutor&) = delete;
CommandExecutor& operator=(const CommandExecutor&) = delete;
CommandExecutor(CommandExecutor&&) = default;
CommandExecutor& operator=(CommandExecutor&&) = default;
~CommandExecutor() = default;
std::string execute() {
if (!m_pipe) {
throw std::runtime_error("Command not initialized!");
}
std::array<char, 128> buffer;
std::string result;
while (fgets(buffer.data(), static_cast<int>(buffer.size()),
m_pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
private:
std::unique_ptr<FILE, void (*)(FILE*)> m_pipe{nullptr, [](FILE* file) { if (file) { PCLOSE(file); } }};
};