Repository navigation
Expand file tree
/
Copy pathmyshell_part3.cpp
More file actions
72 lines (61 loc) · 1.6 KB
/
Copy pathmyshell_part3.cpp
File metadata and controls
72 lines (61 loc) · 1.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
//
// Created by ayaz1 on 01-10-2025.
//
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <unistd.h> // For fork(), execvp()
#include <sys/wait.h> // For waitpid()
std::vector<std::string> parse_line(const std::string& line) {
std::vector<std::string> tokens;
std::stringstream ss(line);
std::string token;
while (ss >> token) {
tokens.push_back(token);
}
return tokens;
}
int main() {
std::string input_line;
while (true) {
std::cout << "myshell> ";
if (!std::getline(std::cin, input_line)) {
std::cout << std::endl;
break;
}
std::vector<std::string> args = parse_line(input_line);
if (args.empty()) {
continue;
}
if (args[0] == "exit") {
break;
} else if (args[0]=="cd") {
if (args.size()<2){
std::cerr << "cd: expected argument to \"cd\"" << std::endl;
} else {
if (chdir(args[1].c_str()) != 0) {
perror("cd");
}
}
continue;
}
std::vector<char*> c_args;
for (auto& arg : args) {
c_args.push_back(&arg[0]);
}
c_args.push_back(nullptr);
pid_t pid = fork();
if (pid == 0) {
execvp(c_args[0], c_args.data());
perror("execvp");
exit(EXIT_FAILURE);
} else if (pid > 0) {
int status;
waitpid(pid,&status,0);
} else {
perror("fork");
}
}
return 0;
}