#include #include #include #include #include #include #include using namespace std; void ParseCmd(string cmd, vector & line); int main() { //pid_t subproc; string cmd; string prompt{"DASH > "}; char * myArgs[10]; myArgs[0] = NULL; char * myEnvp[3]; myEnvp[0] = strdup("SHELL=DASH"); myEnvp[1] = strdup("USER=confused"); myEnvp[2] = NULL; cout << prompt; getline(cin, cmd); while (cmd != "exit") { pid_t pid; int code; size_t argc; size_t linePos; vector line; ParseCmd(cmd, line); pid = fork(); if (pid == 0) { argc = 0; linePos = 0; while (argc < 9 and linePos < line.size()) { if (line [linePos] == "<") { linePos++; if (linePos < line.size()){ close(STDIN_FILENO); open(line[linePos].c_str(), O_RDONLY); linePos++; } } else if (line[linePos] == ">") { linePos++; if (linePos < line.size()) { close(STDOUT_FILENO); open(line[linePos].c_str(), O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR); linePos++; } } else { myArgs[argc] = strdup(line[linePos].c_str()); argc ++; linePos++; } } myArgs[argc] = NULL; code = execvpe(line[0].c_str(), myArgs, myEnvp); if (code == -1) { perror("exec failed"); } return 1; } else { int status; code = wait(&status); if (code == -1) { if (errno == ECHILD) { cout << " I bet the exec failed" << endl; } else { perror("wait failed"); } } } cout << prompt; getline(cin, cmd); } free (myEnvp[0]); free (myEnvp[1]); return 0; } void ParseCmd(string cmd, vector & line) { size_t pos; pos = cmd.find(' '); while (pos != string::npos) { string subcmd = cmd.substr(0, pos); if (subcmd != "") { line.push_back(subcmd); if (pos != string::npos) { cmd = cmd.substr(pos+1); } else { cmd = ""; } } pos = cmd.find(' '); } if (cmd != "") { line.push_back(cmd); } }