-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart_process.cpp
More file actions
98 lines (84 loc) · 2.99 KB
/
Copy pathstart_process.cpp
File metadata and controls
98 lines (84 loc) · 2.99 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
/*
******************* Assignment #2: XSH ********************
******************* CS480, Summer 2024 ********************
Aeron Flores (826123084) and Jasmine Rasmussen (129935517)
***** Edoras #s: Aeron - CSSC4404; Jasmine - CSSC4427 *****
******************** start_process.cpp ********************
*/
#include "xsh_shell.h"
void startProcess(const std::string& userInput){
std::vector<std::string> commands;
std::istringstream stream(userInput);
std::string command;
// Split input at pipes
while (std::getline(stream, command, '|')) {
commands.push_back(command);
}
// Variable to hold number of commands in stream
// Pipefds: multiple pairs of file descriptors
int numCommands = commands.size();
int pipefds[2 * (numCommands - 1)];
// Create pipes by connecting the output command
// pipefds[i * 2] to be read by the input pipefds[i * 2 + 1]
for (int i = 0; i < (numCommands - 1); ++i) {
if (pipe(pipefds + i * 2) < 0) {
std::perror("pipe");
std::exit(EXIT_FAILURE);
}
}
int pid;
int j = 0;
for (int i = 0; i < numCommands; ++i) {
pid = fork();
// Child process
if (pid == 0) {
// Redirect input from previous command
if (i != 0) {
if (dup2(pipefds[j - 2], 0) < 0) {
std::perror("dup2");
std::exit(EXIT_FAILURE);
}
}
// Redirect output to next command
if (i != numCommands - 1) {
if (dup2(pipefds[j + 1], 1) < 0){
std::perror("dup2");
std::exit(EXIT_FAILURE);
}
}
// Close all pipe file descriptors
for (int k = 0; k < 2 * (numCommands - 1); ++k) {
close(pipefds[k]);
}
// Split the command into arguments
std::istringstream cmdStream(commands[i]);
std::vector<std::string> args;
std::string arg;
while (cmdStream >> arg) {
args.push_back(arg);
}
// Convert arguments to char* array
std::vector<char*> argv(args.size() + 1);
for (size_t k = 0; k < args.size(); ++k) {
argv[k] = &args[k][0];
}
// If new process does not replace current process, throw error
if (execvp(argv[0], argv.data()) < 0) {
std::perror("execvp");
std::exit(EXIT_FAILURE);
}
} else if (pid < 0) { // Error creating child process
std::perror("fork");
std::exit(EXIT_FAILURE);
}
j += 2;
}
// Close all pipe file descriptors in the parent process
for (int i = 0; i < 2 * (numCommands - 1); ++i) {
close(pipefds[i]);
}
// Wait for all child processes to finish
for (int i = 0; i < numCommands; ++i) {
wait(NULL);
}
}