This commit is contained in:
Ben Harris 2016-10-31 13:53:32 -04:00
parent c3d380a394
commit 3c45441bf9
2 changed files with 37 additions and 19 deletions

54
bish.cc Normal file → Executable file
View File

@ -8,9 +8,6 @@
#include <sys/types.h>
using namespace std;
// globals
// const char **args;
// util methods
vector<string> split(const char *str, char c = ' '){
vector<string> result;
@ -22,12 +19,13 @@ vector<string> split(const char *str, char c = ' '){
return result;
}
void parse_args_vector(vector<string> vargs, char*** args) {
void parse_args(vector<string> vargs, char*** args) {
*args = (char**)malloc((vargs.size()+1)*sizeof(char*));
int i = 0;
for(auto it = vargs.begin(); it < vargs.end(); ++it, i++) {
// string tmp = *it;
*args[i] = (char *)*it.c_str();
string tmp = *it;
*args[i] = (char *)tmp.c_str();
// cout << *it << endl;
}
*args[vargs.size()] = NULL;
}
@ -40,19 +38,41 @@ int main(int argc, char **argv){
vector<string> path = split(getenv("PATH"), ':');
cout << "bish$ ";
cout << get_current_dir_name() << "$ ";
while (getline(cin, line)) {
parse_args_vector(split(line.c_str()), &args);
if (fork() == 0){
cout << "in da child" << endl;
execv(args[0], args);
perror("fork child process");
parse_args(split(line.c_str()), &args);
// http://www.linuxquestions.org/questions/programming-9/making-a-c-shell-775690/
if (strcmp(args[0], "exit") == 0) return 0;
if (!strcmp(args[0], "cd")) {
if (args[1] == NULL) {
if (chdir("/") < 0) perror("chdir");
}
else {
if (chdir(args[1]) < 0) perror("chdir");
}
} else {
pid_t kidpid = fork();
if (kidpid < 0) {
perror("fork");
return -1;
}
else if (kidpid == 0){
cout << args[0] << endl;
for (auto it: path) {
string searchpath = string() + it + "/" + string(args[0]);
cout << searchpath << endl;
execv(searchpath.c_str(), args);
}
perror("child process");
}
else {
wait(&status);
}
}
else {
cout << "wiating" << endl;
wait(&status);
}
cout << "bish$ ";
cout << get_current_dir_name() << "$ ";
free(args);
}
return 0;

2
simplesh.cc Normal file → Executable file
View File

@ -5,12 +5,10 @@
int main(int argc, char *argv[]) {
char line[MAX_LENGTH];
while (1) {
printf("simplesh$ ");
if (!fgets(line, MAX_LENGTH, stdin)) break;
system(line);
}
return 0;
}