-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.h
71 lines (61 loc) · 1.57 KB
/
run.h
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
/*
Pitágoras Alves & André Winston, UFRN, March 2017.
string run(const char * command):
command Shell command to be executed by linux;
returns A string with all of the output generated by the command
string run(string command):
same as above
void runWhileSilent(vector<string> commands):
commands Vector of commands to be executed in sequence. If one of the commands
outputs anything, the commands after him will be canceled.
*/
#ifndef _RUN_
#define _RUN_
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>
#include <unistd.h>
#include <set>
#include <signal.h>
#include <vector>
using namespace std;
void runWhileSilent(vector<string> commands);
string run(string command);
string run(const char* command);
void runWhileSilent(vector<string> commands){
string output;
for(string cmd : commands){
output = run(cmd);
if(output.length() > 2){
cout << output << endl;
break;
}
}
}
string run(string command){
return run(command.c_str());
}
string run(const char* command){
int bufferSize = 128;
char buff[bufferSize];
string output = "";
FILE *procStream = popen(command, "r");
if(procStream == NULL){
throw std::runtime_error("Could not get process output");
}else{
try{
while (!feof(procStream)){
if (fgets(buff, bufferSize, procStream) != NULL){
output += buff;
}
}
}catch(...){
pclose(procStream);
throw std::runtime_error("Error while getting output of process");
}
pclose(procStream);
return output;
}
}
#endif