-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
349 lines (310 loc) · 11.6 KB
/
Copy pathmain.cpp
File metadata and controls
349 lines (310 loc) · 11.6 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
#include <iostream>
#include <fstream>
#include <sstream>
#include <unistd.h>
#include <sys/wait.h>
#include <vector>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#include <algorithm>
#include "utils.hpp"
#include "logger.hpp"
#include "const.hpp"
using namespace std;
vector<pair<string, string>> list_city_files(const string &stores_dir, Logger &log)
{
vector<pair<string, string>> stores; // pair of city name and file path
DIR *dir;
struct dirent *ent;
if ((dir = opendir(stores_dir.c_str())) != NULL)
{
while ((ent = readdir(dir)) != NULL)
{
string filename = ent->d_name;
// Check if the file is a CSV and not Parts.csv
if (filename.length() > 4 && filename.substr(filename.length() - 4) == ".csv" && filename != "Parts.csv")
{
string city_name = filename.substr(0, filename.length() - 4);
string file_path = stores_dir + "/" + filename;
stores.emplace_back(city_name, file_path);
log.minfo("Found store: " + city_name + " with file: " + file_path);
}
}
closedir(dir);
}
else
{
log.error("Could not open stores directory: " + stores_dir);
}
return stores;
}
int main(int argc, char *argv[])
{
(void)argc;
Logger log("Main");
if (argc != 2)
{
cerr << "Usage: " << argv[0] << " <stores_directory>" << endl;
return 1;
}
string stores_dir = argv[1];
// List all city CSV files in the stores directory
vector<pair<string, string>> stores = list_city_files(stores_dir, log);
if (stores.empty())
{
log.error("No city CSV files found in the stores directory.");
return 1;
}
log.minfo("All city store files scanned successfully.");
// Read Parts.csv from the stores directory
string parts_file = stores_dir + "/Parts.csv";
ifstream parts_fs(parts_file);
if (!parts_fs.is_open())
{
log.error("Failed to open Parts.csv file.");
return 1;
}
string parts_line;
getline(parts_fs, parts_line);
parts_fs.close();
vector<string> all_items = tokenize(parts_line, ',');
if (all_items.empty())
{
log.error("No items found in Parts.csv.");
return 1;
}
log.minfo("Parts file read successfully.");
// Get user input: select items to report
cout << "Available items:" << endl;
for (size_t i = 0; i < all_items.size(); i++)
{
cout << i + 1 << ". " << all_items[i] << endl;
}
cout << "Enter the numbers of items you want to report, separated by space: ";
string input;
getline(cin, input);
vector<string> selected_items;
string selected_items_all_in_str = "";
vector<string> input_tokens = tokenize(input, ' ');
for (auto &tok : input_tokens)
{
try
{
int num = stoi(tok);
if (num >= 1 && num <= (int)all_items.size())
{
selected_items.push_back(all_items[num - 1]);
selected_items_all_in_str = selected_items_all_in_str + all_items[num - 1] + ',';
}
else
{
log.warning("Invalid item number entered: " + tok);
}
}
catch (exception &e)
{
log.warning("Invalid input detected: " + tok);
}
}
if (selected_items.empty())
{
log.error("No valid items selected for reporting.");
return 1;
}
log.minfo("User selected items for reporting.");
for (string item_name : selected_items)
{
string pipe_path = GOODS_PIPE_PREFIX + item_name;
if (mkfifo(pipe_path.c_str(), 0666) == -1)
{
if (errno != EEXIST)
{
log.error("Failed to create named pipe: " + pipe_path);
return 1;
}
}
log.minfo("Named pipe created for good: " + item_name);
}
// --- Create two unnamed pipes for each city (to_child and from_child) ---
vector<pair<int, int>> city_pipes_parent; // (to_child_write, from_child_read)
vector<pair<int, int>> city_pipes_child; // (to_child_read, from_child_write)
for (size_t i = 0; i < stores.size(); i++)
{
int to_child[2], from_child[2];
if (pipe(to_child) == -1 || pipe(from_child) == -1)
{
log.error("Failed to create pipes for city: " + stores[i].first);
return 1;
}
city_pipes_parent.emplace_back(to_child[1], from_child[0]); // Parent writes to_child_write, reads from_child_read
city_pipes_child.emplace_back(to_child[0], from_child[1]); // Child reads to_child_read, writes from_child_write
}
// --- Create two unnamed pipes for each good (to_child and from_child) ---
vector<pair<int, int>> good_pipes_parent; // (to_child_write, from_child_read)
vector<pair<int, int>> good_pipes_child; // (to_child_read, from_child_write)
for (size_t i = 0; i < selected_items.size(); i++)
{
int to_child[2], from_child[2];
if (pipe(to_child) == -1 || pipe(from_child) == -1)
{
log.error("Failed to create pipes for good: " + selected_items[i]);
return 1;
}
good_pipes_parent.emplace_back(to_child[1], from_child[0]); // Parent writes to_child_write, reads from_child_read
good_pipes_child.emplace_back(to_child[0], from_child[1]); // Child reads to_child_read, writes from_child_write
}
// --- Fork City Processes and one write on it with unnammed pipe ---
vector<pid_t> city_pids;
vector<int> read_from_city_fds, write_to_city_fds;
for (size_t i = 0; i < stores.size(); i++)
{
const pair<string, string> &store = stores[i];
pid_t pid = fork();
if (pid < 0)
{
log.error("Failed to fork city process for store: " + store.first);
return 1;
}
if (pid == 0)
{
// --- Child Process: City ---
close(city_pipes_parent[i].first);
close(city_pipes_parent[i].second);
string child_read_head = to_string(city_pipes_child[i].first);
vector<char *> args;
args.push_back(const_cast<char *>(EXE_CITY.c_str())); // argv[0] exe file name for store process
args.push_back(const_cast<char *>(child_read_head.c_str())); // argv[1] read head of store
args.push_back(const_cast<char *>(store.first.c_str())); // argv[2] name of store city
args.push_back(nullptr); // NULL terminator
// Execute the city process
execvp(EXE_CITY.c_str(), args.data());
// If execvp returns, it failed
log.error("Failed to execute city process for store: " + store.first);
exit(1);
}
else
{
// --- Parent Process ---
close(city_pipes_child[i].first);
close(city_pipes_child[i].second);
city_pids.push_back(pid);
read_from_city_fds.push_back(city_pipes_parent[i].second);
int write_to_city_fd = city_pipes_parent[i].first;
// string args;
string args = "";
args = args + store.first + '!'; // name of city
args = args + store.second + '!'; // file of city
string num_items_str = to_string(selected_items.size());
args = args + num_items_str + '!'; // number of selected items
args = args + to_string(city_pipes_child[i].second) + '!'; // write end of store pipe
args = args + selected_items_all_in_str + '!'; // coded string of name of selected items
// args example : Mashhad!stores/Mashhad.csv!2!14!shekar,berenj,!
// Execute the city process
write(city_pipes_parent[i].first, args.c_str(), args.size());
close(write_to_city_fd);
log.minfo("City process spawned for store: " + store.first);
}
}
// --- Fork good Processes and one write on it with unnammed pipe ---
vector<pid_t> good_pids;
vector<int> read_from_good_fds, write_to_good_fds;
for (size_t i = 0; i < selected_items.size(); i++)
{
pid_t pid = fork();
string item = selected_items[i];
if (pid < 0)
{
log.error("Failed to fork goods process for item: " + item);
return 1;
}
if (pid == 0)
{
// --- Child Process: good ---
close(good_pipes_parent[i].first);
close(good_pipes_parent[i].second);
// string child_write_head = to_string(city_pipes_child[i].second);
string child_read_head = to_string(good_pipes_child[i].first);
vector<char *> args;
args.push_back(const_cast<char *>(EXE_GOODS.c_str())); // argv[0] .exe file name
args.push_back(const_cast<char *>(child_read_head.c_str())); // argv[1] read end of good process pipe
args.push_back(const_cast<char *>(item.c_str())); // argv[2] name of good
args.push_back(nullptr); // NULL terminator
// Execute the city process
execvp(EXE_GOODS.c_str(), args.data());
// If execvp returns, it failed
log.error("Failed to execute good process for item: " + item);
exit(1);
}
else
{
// --- Parent Process ---
close(city_pipes_child[i].first);
close(city_pipes_child[i].second);
good_pids.push_back(pid);
read_from_good_fds.push_back(good_pipes_parent[i].second);
int write_to_good_fd = good_pipes_parent[i].first;
string args = "";
args = args + item + '!';
args = args + to_string(good_pipes_child[i].second) + '!';
string size_str = to_string(stores.size());
args = args + size_str + '!'; // count of cities
write(good_pipes_parent[i].first, args.c_str(), args.size());
close(write_to_good_fd);
log.minfo("Good process spawned for item: " + item);
}
}
// -- one read on every city unnamed pipes --
char buffer[MAX_BUFFER_SIZE];
int total_final_profit = 0;
for (auto fd : read_from_city_fds)
{
ssize_t bytes_read = read(fd, buffer, sizeof(buffer) - 1);
if (bytes_read > 0)
{
string msg = buffer;
total_final_profit += stoi(msg);
}
else
{
log.error("Empry message from a city");
}
close(fd);
}
// -- one read on every good unnamed pipes --
for (auto fd : read_from_good_fds)
{
ssize_t bytes_read = read(fd, buffer, sizeof(buffer) - 1);
string total_leftover_of_this_item = buffer;
if (bytes_read > 0)
{
log.output(total_leftover_of_this_item);
}
else
{
log.error("Empry message from a good");
}
close(fd);
}
log.output("Total profits of all stores is " + to_string(total_final_profit)+ "\n");
// --- Cleanup: Remove Named Pipes ---
for (string item_name : selected_items)
{
string pipe_path = GOODS_PIPE_PREFIX + item_name;
if (unlink(pipe_path.c_str()) == 0)
{
log.minfo("Named pipe removed for good: " + item_name);
}
else
{
log.warning("Failed to remove named pipe for good: " + item_name);
}
}
while (wait(NULL) != -1);
log.minfo("Program completed successfully.");
return 0;
}