-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPopen.cpp
More file actions
96 lines (81 loc) · 1.73 KB
/
Copy pathPopen.cpp
File metadata and controls
96 lines (81 loc) · 1.73 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//
// Created by caesar on 2020/1/15.
//
#include <poll_tool.h>
#include "Popen.h"
#ifdef _WIN32
#else
#include <fcntl.h>
#endif
#include <logger.h>
using namespace std;
#ifdef __FILENAME__
const char *Popen::TAG = __FILENAME__;
#else
const char *Popen::TAG = "Popen";
#endif
Popen::Popen(const char *command, const std::vector<std::string> &args) {
command_line = command;
for (const auto &item : args) {
command_line += " " + string("\"") + item + "\"";
}
logger::instance()->i(TAG, __LINE__, "%s", command_line.c_str());
}
Popen::~Popen() {
stop();
}
bool Popen::start() {
#ifdef _WIN32
fp = _popen(command_line.c_str(), "r+");
#else
fp = popen(command_line.c_str(), "r+");
#endif
if (!fp) {
return false;
}
#ifdef _WIN32
#else
fd = fileno(fp);
fcntl(fd, F_SETFL, O_NONBLOCK);
#endif
return true;
}
bool Popen::stop() {
if (!fp) {
#ifdef _WIN32
_pclose(fp);
#else
pclose(fp);
#endif
fp = nullptr;
}
fd = 0;
return true;
}
int Popen::read(string &data, int timeout) {
if (!fp)return -1;
if (poll_tool::check_read_count(fd, timeout) <= 0) {
return 0;
}
char buf[1024] = {};
do {
int ret = ::read(fd, buf, sizeof(buf) - 1);
if (ret == -1 && errno == EAGAIN) {
break;
} else if (ret > 0) {
buf[ret] = 0;
data += buf;
} else {
if (data.empty())
return -1;
else {
break;
}
}
} while (poll_tool::check_read_count(fd, timeout) > 0);
return data.size();
}
int Popen::write(const std::string &data) {
if (!fp)return -1;
return ::write(fd, data.c_str(), data.size());
}