diff --git a/a.out b/a.out deleted file mode 100755 index 59770eb..0000000 Binary files a/a.out and /dev/null differ diff --git a/builds/microshell.o b/builds/microshell.o index 9e5e888..96350c0 100644 Binary files a/builds/microshell.o and b/builds/microshell.o differ diff --git a/microshell b/microshell index 191582a..4d6ea3d 100755 Binary files a/microshell and b/microshell differ diff --git a/microshell.c b/microshell.c index 54d7b34..74c4ad3 100644 --- a/microshell.c +++ b/microshell.c @@ -1,4 +1,4 @@ -#include // write, fork, execve, pipe +#include // write, fork, execve, pipe, chdir #include // printf #include // strcmp #include // pid_t @@ -8,36 +8,37 @@ #define STDOUT 1 #define STDERR 2 -void print_cmd(char **av) -{ - int i; - int size; +typedef enum {FALSE, TRUE} BOOL; - i = 0; - while (av[i]) - { - size = 0; - while (av[i][size] != '\0') - size++; - write(1, av[i], size); - write(1, " ", 1); - i++; - } - write(1, "\n", 1); +void builtin_cd(char *av) +{ + printf("here\n"); + if (av) + chdir(av); } -//void exec_cmd(char **av, int end, char **en) -void exec_cmd(char **av, char **en) +void exec_cmd(char **av, char **en, int fdin, int fdout) { pid_t pid = fork(); -// av[end] = NULL; if (pid == 0) // child process { + if (fdin != STDIN_FILENO) + { + dup2(fdin, STDIN_FILENO); + close(fdin); + } + if (fdout != STDOUT_FILENO) + { + dup2(fdout, STDOUT_FILENO); + close(fdout); + } execve(av[0], av, en); } else // parent process { + if (fdout != STDOUT_FILENO) + close(fdout); waitpid(pid, NULL, 0); } } @@ -46,22 +47,38 @@ int main(int ac, char **av, char **en) { int i; int start; + int fds[2]; + int old_fdin; if (ac <= 1) return (0); i = 1; + old_fdin = STDIN_FILENO; + fds[STDIN] = STDIN_FILENO; + fds[STDOUT] = STDOUT_FILENO; while (i < ac) { start = i; while (i < ac && strcmp(av[i], "|") && strcmp(av[i], ";")) i++; + if (av[i] && !strcmp(av[i], "|")) + pipe(fds); av[i] = NULL; -// print_cmd(&av[start]); - exec_cmd(&av[start], en); + if (strcmp(av[start], "cd") == 0) + builtin_cd(av[start + 1]); + else + exec_cmd(av + start, en, old_fdin, fds[STDOUT]); + if (old_fdin != STDIN_FILENO) + close(old_fdin); + old_fdin = fds[STDIN]; + fds[STDOUT] = STDOUT_FILENO; if (i < ac) i++; } return (0); } -// https://www.rozmichelle.com/pipes-forks-dups/ +// pipes fork and dups : https://www.rozmichelle.com/pipes-forks-dups/ +// subject and example : https://github.com/Glagan/42-exam-rank-04 +// lsof -c microshell : https://www.thegeekstuff.com/2012/08/lsof-command-examples/ +