-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8_pipeline.cpp
More file actions
96 lines (79 loc) · 2.85 KB
/
8_pipeline.cpp
File metadata and controls
96 lines (79 loc) · 2.85 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
#include <iostream>
#include <vector>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <algorithm>
#define MAX_INPUT_SIZE 1024
int main() {
char input[MAX_INPUT_SIZE];
while (1) {
std::cout << "YourShell> ";
if (fgets(input, sizeof(input), stdin) == nullptr) {
break; // Exit on Ctrl+D or EOF
}
// Tokenize input and handle built-in commands (ls, echo, cd, pwd, pinfo) as before
// Check for pipes (|)
std::vector<char*> commands;
char* token = strtok(input, "|");
while (token) {
commands.push_back(token);
token = strtok(nullptr, "|");
}
// Create pipes
int num_pipes = commands.size() - 1;
int pipes[num_pipes * 2]; // Two file descriptors (read and write) for each pipe
for (int i = 0; i < num_pipes; i++) {
if (pipe(pipes + i * 2) == -1) {
perror("pipe");
return 1;
}
}
// Execute commands in the pipeline
pid_t pid;
int input_fd = STDIN_FILENO; // Input for the first command is stdin
for (int i = 0; i < commands.size(); i++) {
char* command = commands[i];
pid = fork();
if (pid == -1) {
perror("fork");
return 1;
} else if (pid == 0) {
// Child process
// Redirect input from the previous command's output (except for the first command)
if (i > 0) {
dup2(input_fd, STDIN_FILENO);
}
// Redirect output to the next command's input (except for the last command)
if (i < num_pipes) {
dup2(pipes[i * 2 + 1], STDOUT_FILENO);
}
// Close all pipe file descriptors in the child process
for (int j = 0; j < num_pipes * 2; j++) {
close(pipes[j]);
}
// Execute the command
if (execvp(command, arguments.data()) == -1) {
perror("execvp");
return 1;
}
} else {
// Parent process
waitpid(pid, nullptr, 0);
// Close the input file descriptor of the previous command
if (i > 0) {
close(input_fd);
}
// Close the output file descriptor of the current command
close(pipes[i * 2 + 1]);
// The next command reads from the current command's output
input_fd = pipes[i * 2];
}
}
// Close all remaining pipe file descriptors in the parent process
for (int i = 0; i < num_pipes * 2; i++) {
close(pipes[i]);
}
}
return 0;
}