workingshell

cpp

School

Drake University *

*We aren’t endorsed by this school

Course

313

Subject

Philosophy

Date

Oct 30, 2023

Type

cpp

Pages

5

Uploaded by MinisterBoulderLobster32

Report
//multiples dont work #include <iostream> #include <vector> #include <string> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <cstring> #include <fcntl.h> #include <sys/stat.h> #include <sys/param.h> #include <pwd.h> #include <ctime> #include "Tokenizer.h" using namespace std; // Function to handle single command execution with I/O redirection void executeSingleCommand(const vector<string>& command, bool is_background, string input_file = "", string output_file = "") { pid_t pid = fork(); if (pid < 0) { perror("fork"); exit(2); } if (pid == 0) { // Child process // Implement checks for I/O redirection and handle them using dup2 if (!input_file.empty()) { int in_fd = open(input_file.c_str(), O_RDONLY); if (in_fd == -1) { perror("open"); exit(2); } dup2(in_fd, 0); close(in_fd); } if (!output_file.empty()) { int out_fd = open(output_file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); if (out_fd == -1) { perror("open"); exit(2); } dup2(out_fd, 1); close(out_fd); } // Create an array of C-style strings from the vector vector<char*> args; for (const string& arg : command) { args.push_back(const_cast<char*>(arg.c_str())); } args.push_back(nullptr); // Execute the command in the child process execvp(args[0], args.data());
perror("execvp"); exit(2); } else { // Parent process if (!is_background) { int status = 0; waitpid(pid, &status, 0); if (status > 1) { exit(status); } } } } void executePipedCommands(const vector<vector<string>>& commands, bool is_background, string input_file = "", string output_file = "") { int prev_pipe_fd[2] = {-1, -1}; int next_pipe_fd[2] = {-1, -1}; for (size_t i = 0; i < commands.size(); ++i) { if (i < commands.size() - 1) { if (pipe(next_pipe_fd) == -1) { perror("pipe"); exit(2); } } pid_t pid = fork(); if (pid < 0) { perror("fork"); exit(2); } if (pid == 0) { // Child process if (i < commands.size() - 1) { close(next_pipe_fd[0]); dup2(next_pipe_fd[1], 1); close(next_pipe_fd[1]); } if (i > 0) { close(prev_pipe_fd[1]); dup2(prev_pipe_fd[0], 0); close(prev_pipe_fd[0]); } // Implement checks for I/O redirection if (i == 0) { if (!input_file.empty()) { int in_fd = open(input_file.c_str(), O_RDONLY); if (in_fd == -1) { perror("open"); exit(2); } dup2(in_fd, 0); close(in_fd); } } if (i == commands.size() - 1) {
if (!output_file.empty()) { int out_fd = open(output_file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); if (out_fd == -1) { perror("open"); exit(2); } dup2(out_fd, 1); close(out_fd); } } // Create an array of C-style strings from the vector vector<char*> args; for (const string& arg : commands[i]) { args.push_back(const_cast<char*>(arg.c_str())); } args.push_back(nullptr); // Execute the command in the child process execvp(args[0], args.data()); perror("execvp"); exit(2); } else { // Parent process if (!is_background) { // Close pipe file descriptors in the parent if (prev_pipe_fd[0] != -1) { close(prev_pipe_fd[0]); } if (prev_pipe_fd[1] != -1) { close(prev_pipe_fd[1]); } int status = 0; waitpid(pid, &status, 0); if (status > 1) { exit(status); } } // Update previous pipe file descriptors if (prev_pipe_fd[0] != -1) { close(prev_pipe_fd[0]); } if (prev_pipe_fd[1] != -1) { close(prev_pipe_fd[1]); } if (i < commands.size() - 1) { prev_pipe_fd[0] = next_pipe_fd[0]; prev_pipe_fd[1] = next_pipe_fd[1]; } } } } int main() {
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
int original_stdin = dup(0); int original_stdout = dup(1); char prevWorkingDir[PATH_MAX]; vector<pid_t> background_pids; if (getcwd(prevWorkingDir, sizeof(prevWorkingDir)) == NULL) { perror("getcwd"); exit(EXIT_FAILURE); } for (;;) { time_t now = time(0); struct tm current_time; char timestamp[80]; current_time = *localtime(&now); strftime(timestamp, sizeof(timestamp), "%Y-%m-d %H:%M:%S", &current_time); struct passwd* pw = getpwuid(getuid()); const char* username = pw->pw_name; char current_dir[PATH_MAX]; if (getcwd(current_dir, sizeof(current_dir)) != NULL) { // Successfully obtained the current working directory } else { perror("getcwd"); exit(EXIT_FAILURE); } cout << "Shell " << timestamp << " " << username << ":" << current_dir << "$ "; string input; getline(cin, input); if (input == "exit") { cout << "Now exiting shell..." << endl << "Goodbye" << endl; break; } bool is_background = false; if (!input.empty() && input[input.length() - 1] == '&') { is_background = true; input.pop_back(); } // Debug: Print the input before tokenization cout << "Input: " << input << endl; if (input == "cd") { // Handle "cd" command without forking a new process if (chdir(getenv("HOME")) == -1) { perror("chdir"); } else { // Save the previous working directory strcpy(prevWorkingDir, current_dir); } } else if (input == "cd -") { // Handle "cd -" command without forking a new process if (prevWorkingDir[0] != '\0') {
if (chdir(prevWorkingDir) == -1) { perror("chdir"); } } else { cerr << "Previous working directory is not set.\n"; } } else if (input.compare(0, 3, "cd ") == 0) { char* newDir = &input[3]; if (chdir(newDir) == -1) { perror("chdir"); } else { // Save the previous working directory strcpy(prevWorkingDir, current_dir); } } else { // Tokenize the user input Tokenizer tknr(input); // Debug: Print parsed commands and associated input/output files for (size_t i = 0; i < tknr.commands.size(); ++i) { cout << "Command " << i << ": "; for (const string& arg : tknr.commands[i]->args) { cout << arg << " "; } cout << "Input file: " << tknr.commands[i]->in_file << " Output file: " << tknr.commands[i]->out_file << endl; } // Check if it's a single command or piped commands if (tknr.commands.size() == 1) { string input_file = tknr.commands[0]->in_file; string output_file = tknr.commands[0]->out_file; executeSingleCommand(tknr.commands[0]->args, is_background, input_file, output_file); } else { // Convert tknr.commands to a vector of vector of strings vector<vector<string>> commandStrings; for (size_t i = 0; i < tknr.commands.size(); ++i) { commandStrings.push_back(tknr.commands[i]->args); } string input_file = tknr.commands[0]->in_file; string output_file = tknr.commands[tknr.commands.size() - 1]- >out_file; executePipedCommands(commandStrings, is_background, input_file, output_file); } } } dup2(original_stdin, 0); dup2(original_stdout, 1); return 0; }

Browse Popular Homework Q&A

Q: 1. Graph the inequality. 22-4 3 3 X-
Q: On the graph input tool, change the number found in the Quantity Demanded field to determine the…
Q: The function f(x) = -2x + 0x² + 150x + 3 is increasing on the interval ( ). It is decreasing on the…
Q: The number of new contributors to a public radio station's annual fund drive over the last ten years…
Q: QUESTION 11 What product would you expect to obtain from addition of C12 to…
Q: determines the rate of return for a certain fund. The standard deviation of the rate of return is…
Q: New share price|NPV > announced] The market cap of the firm is $100 million (10 million shares at…
Q: A pendulum completes 4.4 cycles every second what is its period
Q: A vertically-held sledge hammer is easier to balance when the heavier end is Group of answer choices…
Q: 7. What is the purpose of the delta-wye transform as applied to resistor networks? Give an example…
Q: (1) 10" 12" 2" 5" 2" 2" 8" A992 steel &Mp= ?
Q: A student is using a lathe with 80-hp and 80% efficiency to fabricate a copper alloy with Sy= 1200…
Q: Follow these steps: A. Identify if the problem is inflation or unemployment. If unemployment, state…
Q: (R)-1,2-dibromobutane
Q: Find v(t) for t> 0 if the switch is in position 1 for a long time and moves to position: at t=0.
Q: x² - y² lim (x,y) →(a,a) x² - y² Here a is a constant. (Find the limit assuming x + y) Find the…
Q: ich of the following can be considered units for momentum and impulse? Select more than one.…
Q: QUESTION 19 Which of the following states is not correct. The following species a. formed when…
Q: 7. Effect of a tax on buyers and sellers The following graph shows the daily market for shoes.…
Q: Calculate the mass in grams of each sample. Express your answer using two significant figures.…
Q: 1. A. Hoover dam is located 275 miles from Los Angeles and it supplies 60 Hz power to the city. Can…
Q: A 0.26-kg rock is thrown vertically upward from the top of a cliff that is 32 m high. When it hits…