-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
798 lines (706 loc) · 19.6 KB
/
main.cpp
File metadata and controls
798 lines (706 loc) · 19.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
#include <iostream>
#include <string>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
#include <sstream>
#include <array>
#include <signal.h>
#include <errno.h>
#include <cctype>
#include <termios.h>
std::string redner_prompt(const std::string &homePath);
std::vector<std::string> tokenize_prompt(const std::string &command);
bool handle_builtin(const std::vector<std::string> &tokens, const std::string &homePath);
void run_external(const std::vector<std::string> &tokens);
std::vector<char *> make_args(const std::vector<std::string> &tokens);
bool check_has_pipe(const std::vector<std::string> &tokens);
std::vector<std::vector<std::string>> parse_pipeline(const std::vector<std::string> &tokens);
pid_t run_pipeline(const std::vector<std::vector<std::string>> &pipeline);
void reap_background_jobs();
void print_jobs();
int find_job_by_id(int job_id);
int find_last_job();
void wait_for_foreground_job(pid_t pgid, const std::string &command);
void cleanup_done_jobs();
void init_shell_job_control();
void put_job_in_foreground(pid_t pgid, const std::string &command);
int parse_job_id_token(const std::string &token, const std::string &builtin_name);
void sigchld_handler(int);
struct Job {
int job_id;
pid_t pgid;
std::string cmdline;
enum Status { RUNNING, STOPPED, DONE } status;
};
std::vector<Job> jobs;
int shell_terminal = STDIN_FILENO;
pid_t shell_pgid = 0;
volatile sig_atomic_t child_flag = 0;
void sigchld_handler(int)
{
child_flag = 1;
}
int parse_job_id_token(const std::string &token, const std::string &builtin_name)
{
if (token.empty())
{
std::cerr << builtin_name << ": expected job id like %1 or 1\n";
return -1;
}
std::string numeric_part = token;
if (numeric_part[0] == '%')
{
if (numeric_part.size() == 1)
{
std::cerr << builtin_name << ": expected job id after %\n";
return -1;
}
numeric_part = numeric_part.substr(1);
}
try
{
size_t used = 0;
int job_id = std::stoi(numeric_part, &used);
if (used != numeric_part.size() || job_id <= 0)
{
std::cerr << builtin_name << ": expected job id like %1 or 1\n";
return -1;
}
return job_id;
}
catch (...)
{
std::cerr << builtin_name << ": expected job id like %1 or 1\n";
return -1;
}
}
void init_shell_job_control()
{
if (!isatty(shell_terminal))
{
return;
}
shell_pgid = getpid();
if (setpgid(shell_pgid, shell_pgid) < 0 && errno != EACCES)
{
perror("setpgid");
}
if (tcsetpgrp(shell_terminal, shell_pgid) < 0)
{
perror("tcsetpgrp");
}
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGTSTP, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
}
void put_job_in_foreground(pid_t pgid, const std::string &command)
{
if (isatty(shell_terminal))
{
if (tcsetpgrp(shell_terminal, pgid) < 0)
{
perror("tcsetpgrp");
}
}
wait_for_foreground_job(pgid, command);
if (isatty(shell_terminal))
{
if (tcsetpgrp(shell_terminal, shell_pgid) < 0)
{
perror("tcsetpgrp");
}
}
}
const char *job_status_to_string(Job::Status status);
const char *job_status_to_string(Job::Status status)
{
if (status == Job::RUNNING)
{
return "Running";
}
if (status == Job::STOPPED)
{
return "Stopped";
}
return "Done";
}
int find_job_by_id(int job_id)
{
for (int i = 0; i < (int)jobs.size(); i++)
{
if (jobs[i].job_id == job_id)
{
return i;
}
}
return -1;
}
int find_last_job()
{
if (jobs.empty())
{
return -1;
}
return (int)jobs.size() - 1;
}
void print_jobs()
{
for (const auto &job : jobs)
{
std::cout << "[" << job.job_id << "] " << job.pgid << " " << job_status_to_string(job.status) << " " << job.cmdline << "\n";
}
}
void cleanup_done_jobs()
{
std::vector<Job> active_jobs;
for (const auto &job : jobs)
{
if (job.status != Job::DONE)
{
active_jobs.push_back(job);
}
}
jobs = active_jobs;
for (int i = 0; i < (int)jobs.size(); i++)
{
jobs[i].job_id = i + 1;
}
}
void reap_background_jobs()
{
for (auto &job : jobs)
{
int status;
bool saw_state_change = false;
bool saw_exit = false;
pid_t pid;
while ((pid = waitpid(-job.pgid, &status, WNOHANG | WUNTRACED | WCONTINUED)) > 0)
{
saw_state_change = true;
if (WIFSTOPPED(status))
{
job.status = Job::STOPPED;
}
else if (WIFCONTINUED(status))
{
job.status = Job::RUNNING;
}
else if (WIFEXITED(status) || WIFSIGNALED(status))
{
saw_exit = true;
}
}
if (!saw_state_change)
{
continue;
}
if (saw_exit)
{
pid_t still_running = waitpid(-job.pgid, &status, WNOHANG);
if (still_running == -1 && errno == ECHILD)
{
job.status = Job::DONE;
std::cout << "\n[" << job.job_id << "] Done " << job.cmdline << "\n";
}
}
}
}
void wait_for_foreground_job(pid_t pgid, const std::string &command)
{
int status;
while (true)
{
pid_t pid = waitpid(-pgid, &status, WUNTRACED);
if (pid < 0)
{
if (errno == EINTR)
{
continue;
}
if (errno == ECHILD)
{
break;
}
perror("waitpid");
break;
}
if (WIFSTOPPED(status))
{
int existing_index = -1;
for (int i = 0; i < (int)jobs.size(); i++)
{
if (jobs[i].pgid == pgid)
{
existing_index = i;
break;
}
}
if (existing_index >= 0)
{
jobs[existing_index].status = Job::STOPPED;
std::cout << "\n[" << jobs[existing_index].job_id << "] Stopped\n";
}
else
{
jobs.push_back({(int)jobs.size() + 1, pgid, command, Job::STOPPED});
std::cout << "\n[" << jobs.size() << "] Stopped\n";
}
break;
}
// for exited/signaled children, keep waiting until group is gone (ECHILD)
}
}
int main()
{
// this sets the homepath. it can be used for a lot of things in a real shell
// for now we use it to format the paths while the program runs and a direct way to get
// back to the initial path by just typing cd, which is a shell feature.
char buffer[FILENAME_MAX];
std::string homePath;
if (getcwd(buffer, sizeof(buffer)) != NULL)
{
homePath = buffer;
}
else
{
perror("getcwd() error");
return 1;
}
init_shell_job_control();
struct sigaction chld_action;
chld_action.sa_handler = sigchld_handler;
sigemptyset(&chld_action.sa_mask);
chld_action.sa_flags = 0;
if (sigaction(SIGCHLD, &chld_action, nullptr) < 0)
{
perror("sigaction(SIGCHLD)");
return 1;
}
while (true)
{
if (child_flag)
{
child_flag = 0;
reap_background_jobs();
cleanup_done_jobs();
}
std::cout << redner_prompt(homePath);
std::string command;
errno = 0;
if (!std::getline(std::cin, command))
{
if (errno == EINTR)
{
std::cin.clear();
continue;
}
break;
}
std::vector<std::string> tokens = tokenize_prompt(command);
bool has_pipe = check_has_pipe(tokens);
// ugly ahh piece of policy check
if (has_pipe && tokens[0] == "cd")
{
std::cerr << "cd: cannot be piped\n";
return 1;
}
// if (has_pipe)
// {
// // parse pipeline
// auto pipeline = parse_pipeline(tokens);
// // execture pipeline
// run_pipeline(pipeline);
// }
bool background = false;
if (!tokens.empty() && tokens.back() == "&") {
background = true;
tokens.pop_back();
}
if (not(handle_builtin(tokens, homePath)))
{
//single commands are also pipelines so no need for seperate execution
auto pipeline = parse_pipeline(tokens);
pid_t pgid = run_pipeline(pipeline);
if (background)
{
jobs.push_back({(int)jobs.size()+1, pgid, command, Job::RUNNING});
std::cout << "[" << jobs.size() << "] " << pgid << "\n";
}
else
{
put_job_in_foreground(pgid, command);
}
}
std::cout << "\n";
}
return 0;
}
// pre: takes in a const refernce for the homepath
std::string redner_prompt(const std::string &homePath)
{
// make the buffer that can hold the path. gotta do this c style for some reason
char buffer[FILENAME_MAX];
std::string shell = "shell>";
std::string path;
// we are not doing the perror thing here cuz seperation of concerns is a good practice
// a function that computes the string should not be doing error stuff, especially in a shell
// program as it will pollute the shell. also getcwd rarely fails
if (getcwd(buffer, sizeof(buffer)) == NULL)
{
return shell;
}
// turn the buffer into a string for comparisons and use homepath for formatting
std::string cwd(buffer);
if (cwd == homePath)
{
path = "~";
}
else if (cwd.find(homePath) == 0)
{
cwd.erase(0, homePath.size());
path = "~" + cwd;
}
else
{
path = std::string(buffer);
}
return path + "\n" + shell;
}
// post: returns the prompt.
// pre: takes in a const reference of a command
std::vector<std::string> tokenize_prompt(const std::string &command)
{
std::vector<std::string> tokens;
std::string token;
bool in_single_quote = false;
bool in_double_quote = false;
bool escaping = false;
auto flush_token = [&]()
{
if (token.empty())
{
return;
}
tokens.push_back(token);
token.clear();
};
for (char c : command)
{
if (escaping)
{
token.push_back(c);
escaping = false;
continue;
}
if (c == '\\')
{
escaping = true;
continue;
}
if (in_single_quote)
{
if (c == '\'')
{
in_single_quote = false;
}
else
{
token.push_back(c);
}
continue;
}
if (in_double_quote)
{
if (c == '"')
{
in_double_quote = false;
}
else
{
token.push_back(c);
}
continue;
}
if (c == '\'')
{
in_single_quote = true;
continue;
}
if (c == '"')
{
in_double_quote = true;
continue;
}
if (std::isspace(static_cast<unsigned char>(c)))
{
flush_token();
continue;
}
if (c == '|' || c == '&')
{
flush_token();
tokens.push_back(std::string(1, c));
continue;
}
token.push_back(c);
}
if (escaping)
{
token.push_back('\\');
}
if (in_single_quote || in_double_quote)
{
std::cerr << "parse error: unmatched quote\n";
return {};
}
flush_token();
return tokens;
}
// post: returns a string vector of tokens fromt the command
// pre takes in the tokens and the homePath(mostly for the cd to be able to return to home easily)
bool handle_builtin(const std::vector<std::string> &tokens, const std::string &homePath)
{
if (tokens.empty())
{
return true; // nothing to do
}
if (tokens[0] == "cd")
{
if (tokens.size() == 1)
{
if (chdir(homePath.c_str()) != 0)
{
perror(("cd: " + homePath).c_str());
}
}
else
{
std::string path;
for (size_t i = 1; i < tokens.size(); i++)
{
path += tokens[i];
}
if (chdir(path.c_str()) != 0)
{
perror(("cd: " + path).c_str());
}
}
return true;
}
if (tokens[0] == "exit")
{
exit(0);
}
if (tokens[0] == "jobs")
{
print_jobs();
return true;
}
if (tokens[0] == "fg")
{
int index = -1;
if (tokens.size() == 1)
{
index = find_last_job();
}
else
{
int job_id = parse_job_id_token(tokens[1], "fg");
if (job_id < 0)
{
return true;
}
index = find_job_by_id(job_id);
}
if (index < 0 || index >= (int)jobs.size())
{
std::cerr << "fg: no such job\n";
return true;
}
Job job = jobs[index];
jobs.erase(jobs.begin() + index);
kill(-job.pgid, SIGCONT);
std::cout << job.cmdline << "\n";
put_job_in_foreground(job.pgid, job.cmdline);
return true;
}
if (tokens[0] == "bg")
{
int index = -1;
if (tokens.size() == 1)
{
index = find_last_job();
}
else
{
int job_id = parse_job_id_token(tokens[1], "bg");
if (job_id < 0)
{
return true;
}
index = find_job_by_id(job_id);
}
if (index < 0 || index >= (int)jobs.size())
{
std::cerr << "bg: no such job\n";
return true;
}
kill(-jobs[index].pgid, SIGCONT);
jobs[index].status = Job::RUNNING;
std::cout << "[" << jobs[index].job_id << "] " << jobs[index].cmdline << " &\n";
return true;
}
return false;
}
// post: returns true if the command was handled by the function, i.e. it was builtin, false otherwise
// pre takes in const reference of tokens for the command
//we dont use this now. one command is just a pipeline with one command.
// void run_external(const std::vector<std::string> &tokens)
// {
// pid_t pid = fork();
// if (pid < 0)
// {
// perror("fork failed");
// return;
// }
// else if (pid == 0)
// {
// if (tokens.empty())
// _exit(0); // always do this in child if not using exec
// std::vector<char *> argv = make_args(tokens);
// execvp(argv[0], argv.data());
// perror("execvp");
// }
// else
// {
// int status;
// waitpid(pid, &status, 0);
// }
// }
// post has succesfully run the child process with the command
// pre accepts list of tokens that contain the command as a vector of strings
std::vector<char *> make_args(const std::vector<std::string> &tokens)
{
std::vector<char *> argv;
for (auto &s : tokens)
{
argv.push_back(const_cast<char *>(s.c_str()));
}
argv.push_back(nullptr);
return argv;
}
// post: returns a vector of const char* type tokens which can be fed into the C posix api
//pre: takes in a vector of tokens of the command
bool check_has_pipe(const std::vector<std::string> &tokens)
{
for (const auto &t : tokens)
{
if (t == "|")
{
return true;
}
}
return false;
}
//post: returns a bool value whether the command had the pipe symbol which can be used to execute the pipeline path in main
//pre: takes in tokens
std::vector<std::vector<std::string>> parse_pipeline (const std::vector<std::string> &tokens)
{
std::vector<std::vector<std::string>> pipeline;
std::vector<std::string> command;
for(const auto &t: tokens){
if(t == "|")
{
pipeline.push_back(command);
command.clear();
}
else
{
command.push_back(t);
}
}
pipeline.push_back(command);
return pipeline;
}
//post: returns pipeline which is basically all commands of the pipe command as seperate vector of vector of strings so that each command is seperate.
//looks like {{tokenized command 1}, {tokenized command 2}...{tokenize command n}}
//pre: takes in pipeline which is a vector of vector of each command of the pipeline
//looks like {{tokenized command 1}, {tokenized command 2}...{tokenize command n}}
pid_t run_pipeline(const std::vector<std::vector<std::string>> &pipeline)
{
int n = pipeline.size();
//create n-1 pipes for n commands
std::vector<std::array<int, 2>> pipes(n-1);
for(int i = 0; i < n-1; i++)
{
pipe(pipes[i].data());
}
pid_t pgid = 0;
//fork and run n commands
for(int i = 0; i < n; i++)
{
pid_t pid = fork();
if(pid == 0)
{
if(pgid == 0)//the first process becomes leader of this group
{
pgid = getpid();
}
setpgid(0, pgid);
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
signal(SIGTTIN, SIG_DFL);
signal(SIGTTOU, SIG_DFL);
//if i > 1 meaning these are middle command and the end command they will take input from pipe[n-1]
if(i>0)
{
dup2(pipes[i-1][0],STDIN_FILENO);
}
// if i < n-1 then these are either the first command or the middle commands so they put outputs in a pipe
if(i<n-1)
{
dup2(pipes[i][1], STDOUT_FILENO);
}
//now we close all the pipes for THIS specific child
for(auto &p: pipes)
{
close(p[0]);
close(p[1]);
}
//now we execute shit like real DAWGS
auto argv = make_args(pipeline[i]);
execvp(argv[0],argv.data());
perror("execvp");
_exit(1);
}
else {
if (pgid == 0) {
pgid = pid; // first child becomes leader
}
setpgid(pid, pgid);
}
}
//now its time for the parent to close all the pipes to make sure EOF happens so that we dont get hung
//by random commands that dont work until they get EOF. what that means. who knows.
//remember each process clones all the pipes and stuff INCLUDING THE PARENT
for(auto &p: pipes)
{
close(p[0]);
close(p[1]);
}
//and now we wait.
//here we will use the wait(nullptr) cuz it allows us to run each child concurently instead of serially, which is needed
//for piping to work. Hence above we didnt write else for each if(pid == 0) cuz in case of parent it just starts the second
// child and the third and so on all while the first child is still running and here after all is done it comes to wait
// for(int i = 0; i<n;i++)
// {
// wait(nullptr);
// }
//here we have a new process cuz we will need process groups now instead of a single process type shit.
return pgid;
}
//post: runs the pipeline succesfully piping output of one into input of the other till all execution is completed.