cd builtin ok

This commit is contained in:
hugogogo
2022-06-27 22:41:14 +02:00
parent 14130caef7
commit 078dba820d
4 changed files with 39 additions and 22 deletions

BIN
a.out

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -1,4 +1,4 @@
#include <unistd.h> // write, fork, execve, pipe
#include <unistd.h> // write, fork, execve, pipe, chdir
#include <stdio.h> // printf
#include <string.h> // strcmp
#include <sys/types.h> // 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/