cd3017acb0a2cb4a323d60c0975a6fb8f9d8c9fd
[m6w6/libmemcached] / test / lib / Shell.cpp
1 #include "Shell.hpp"
2
3 #include <cstdlib>
4 #include <unistd.h>
5
6 bool Shell::run(const string &command_, string &output) {
7 auto command = prepareCommand(command_);
8 auto *file = popen(command.c_str(), "r");
9
10 if (!file) {
11 perror("Shell::run popen()");
12 return false;
13 }
14
15 do {
16 char data[1U<<12U];
17 auto read = fread(data, 1, sizeof(data), file);
18
19 if (read) {
20 output.append(data, read);
21 }
22 if (ferror(file)) {
23 cerr << "Shell::run read(): " << strerror(ferror(file));
24 break;
25 }
26 } while (!feof(file));
27
28 auto error = ferror(file);
29 auto status = pclose(file);
30 return !error && !status;
31 }
32
33 bool Shell::run(const string &command) {
34 auto error = system(prepareCommand(command).c_str());
35 if (error == -1) {
36 perror("Shell::run system()");
37 return false;
38 }
39 return !error;
40 }
41
42 Shell::Shell(bool redirect_stderr)
43 : redirect{redirect_stderr}
44 {
45 if (!system(nullptr)) {
46 throw runtime_error("no shell available");
47 }
48 }
49
50 Shell::Shell(const string &prefix_, bool redirect_stderr)
51 : prefix{prefix_}
52 , redirect{redirect_stderr}
53 {
54 if (!system(nullptr)) {
55 throw runtime_error("no shell available");
56 }
57 }
58
59 string Shell::prepareCommand(const string &command_) {
60 string command;
61 if (prefix.length()) {
62 command.append(prefix);
63 command.append("/");
64 }
65 command.append(command_);
66 if (redirect) {
67 command.append(" 2>&1");
68 }
69 INFO("Prepared command: " << command);
70 return command;
71 }