-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshapeMaster.cpp
More file actions
234 lines (215 loc) · 7.05 KB
/
Copy pathshapeMaster.cpp
File metadata and controls
234 lines (215 loc) · 7.05 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/*
* shapeMaster.cpp
*
* Created on: Nov 10, 2016
* Author: alex
*/
#include <iostream>
#include <sstream>
#include <fstream>
#include <cstdlib> // atof
#include <cstdio>
#include <cerrno>
#include <cmath> // ceil()
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h> // [mkfifo();]
#include <time.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <limits.h> // PIPE_BUF http://man7.org/linux/man-pages/man7/pipe.7.html
#include "shapeHelperFunctions.h"
using namespace std;
int main(int argc,char **argv) {
cout << "Program |shapeMaster| is running " << endl;
srand(time(NULL));
char *inputBinaryFile,*tmpdir;
int workersCount = 0;
if (argc != 7) {
cerr << "ERROR : Wrong arguments for main.cpp(utilityX)!" << endl;
cerr << "EXAMPLE : ./shapes -i InputBinaryFile -w WorkersCount -d TempDir" << endl;
exit(EXIT_FAILURE);
}
else {
int i = 1;
while (i < argc) {
if (strncmp(argv[i],"-i",2) == 0) {
inputBinaryFile = argv[i + 1];
}
else if (strncmp(argv[i],"-w",2) == 0) {
workersCount = atoi(argv[i + 1]);
if (workersCount == 0) {
cerr << "ERROR : Program can't run with 0 workers.Exiting,try again" << endl;
exit(EXIT_FAILURE);
}
}
else if (strncmp(argv[i],"-d",2) == 0) {
tmpdir = Strduplicate(argv[i + 1]);
// append '/' as last char if missed by user
int length = strlen(tmpdir);
if (tmpdir[length - 1] != '/') {
tmpdir[length] = '/';
tmpdir[length + 1] = '\0';
}
}
cout << argv[i] << endl;
i = i + 2;
}
}
cout << "Arguments : inputBinaryFile : " << inputBinaryFile << endl
<< "Amount of workers : " << workersCount << endl
<< "Temporal Directory : " << tmpdir << endl;
Check_directory(tmpdir);
ifstream ifile (inputBinaryFile, ios::in | ios::binary);
int totalPoints = 0;
if ( ifile.is_open() ) {
ifile.seekg(0, ios::end);
int length = ifile.tellg();
totalPoints = length/8; // 8 = 2 * 4 (= bytes of float)
}
else
perror ("Failed to open InputFile\n");
ifile.close();
cout << "Total points read :" << totalPoints << endl;
// Round up so last worker won't miss any points at the end of file
int pointsPerWorker = ceil(totalPoints/(float)workersCount);
cout << "Points per Worker :" << pointsPerWorker << endl;
string line;
bool exitFlag = false;
do {
int commandCount = 1;
getline(cin,line);
if (line == "exit")
break;
string token;
for (uint i = 0 ; i < line.length() ; i++) {
if (line[i] == ',')
commandCount++;
if (line[i] == ';') // erase everything after ';'
line.resize(i);
}
cout << "commandCount : " << commandCount << endl;
string nameOfScript = Create_GnuScript(tmpdir,commandCount);
stringstream ss(line);
// splitting line by comma(s)(',')
int numOfHandler = commandCount;
while (getline(ss,token,',')) {
if (token == "exit") {
exitFlag = true;
break;
}
/* Create handlers based on how many commas(=commands) exist */
pid_t pidHandler = fork();
numOfHandler--;
if (!pidHandler) { // if child = handler
/* String manipulation */
pidHandler = getpid();
size_t found = token.find_last_of(" ");
string colour = token.substr(found + 1);
token.resize(found); // erasing colour from string
found = token.find_first_of(" ");
string utilityName = token.substr(0,found);
string utilityPath = Get_cwd(utilityName);
token = token.substr(found + 1); // erasing utilityName from string
Append_GnuScript(nameOfScript,colour,getpid(),tmpdir,numOfHandler);
const char *nameOfFifos[workersCount];
for (int j = 0; j < workersCount; j++) {
// Create fifo name and fifo itself
stringstream nameOfFifo;
nameOfFifo << tmpdir << getpid() << "_w" << j << ".fifo";
const char *fifoName = nameOfFifo.str().c_str();
if (mkfifo(fifoName, 0622) == -1) {
if ( errno != EEXIST) {
char errorbuf[64];
sprintf(errorbuf, "mkfifo. Name : %s", fifoName);
perror(errorbuf);
exit(EXIT_FAILURE);
}
}
nameOfFifos[j] = Strduplicate(fifoName);
}
WorkersID* wid = (WorkersID*) malloc(workersCount * sizeof(WorkersID));
/* Create N workers */
for (int j = 0; j < workersCount; j++) {
pid_t pidWorker = fork();
if (!pidWorker) { // if worker do exec
stringstream tokenwords(token);
int argcUtility = GetArgs(utilityName);
if (argcUtility == -1) // wrong name so child must exit
exit(EXIT_FAILURE);
// -i + -o + -f + -n + -a & floats + NULL
int argcExec = 2 + 2 + 2 + 2 + 1 + argcUtility + 1;
char *argvExec[argcExec];
Create_ExecArgv(argvExec,inputBinaryFile,nameOfFifos[j],j,utilityPath.c_str(),pointsPerWorker,tokenwords);
for (int k = 0 ; k < argcExec ; k++)
cout << argvExec[k] << endl;
execvp(argvExec[0],argvExec);
cout << "EXEC FAILED ON WORKER #" << getpid() << "with arguments :" << endl;
for (int k = 0; k < argcExec; k++) {
cout << argvExec[k] << endl;
}
exit(EXIT_FAILURE);
} else {
if (pidHandler != getpid()) // destroy rest useless handlers
exit(0);
cout << "Handler #" << getpid() << " created Worker #" << pidWorker << endl;
wid[j].workerNum = j;
wid[j].workerPID = pidWorker;
}
}
/* HANDLER WORK */
// Open and read from fifos
int fdarr[workersCount];
for (int j = 0; j < workersCount; j++) {
if ((fdarr[j] = open(nameOfFifos[j], O_RDONLY | O_NONBLOCK )) < 0) {
char errorbuf[64];
sprintf(errorbuf,"Open_fifo : %s",nameOfFifos[j]);
perror(errorbuf);
exit(EXIT_FAILURE);
}
}
// Create & open output file
stringstream outputSS;
outputSS << tmpdir << getpid() << ".out";
const char *outFile = outputSS.str().c_str();
ofstream output(outFile , ios::out);
if (output.is_open()) {
int status,bytes_r,childrenNum = workersCount;
char stringRead[PIPE_BUF];
pid_t pid;
while (childrenNum > 0) {
pid = wait(&status);
int num = ReturnWorkerID(wid,workersCount,pid);
if ((bytes_r = read(fdarr[num],stringRead,PIPE_BUF)) > 0) { //Read string characters
stringRead[bytes_r] = '\0'; //Zero terminator
cout << "Handler #" << getpid() << " received |" << bytes_r << "| bytes" << endl;// << stringRead << endl;
fflush(stdout);
output << stringRead;
memset(stringRead,0,PIPE_BUF);
}
close(fdarr[num]);
childrenNum--; // 'Remove' children
}
} else
cerr << "Handler #" << getpid() << " couldnt open output file!" << endl;
output.close();
free(wid);
exit(1);
}
cout << "Parent #" << getpid() << " created Handler #" << pidHandler << endl; // Child can keep going and fork once
wait(NULL); // wait for handlers to finish
Exec_GnuScript(commandCount,tmpdir);
}
if (exitFlag == true)
break;
} while(!cin.eof());
Remove_all(tmpdir);
free(tmpdir);
cout << "Program |shapes| has been terminated successfully" << endl;
exit(EXIT_SUCCESS);
}