-
Notifications
You must be signed in to change notification settings - Fork 0
/
microshell.c
95 lines (88 loc) · 2.7 KB
/
microshell.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* microshell.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fballest <fballest@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/03/31 11:16:22 by fballest #+# #+# */
/* Updated: 2022/03/31 11:20:28 by fballest ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int ft_strlen(char *str)
{
int i = 0;
while(str[i])
i++;
return(i);
}
void ft_error(void)
{
write(2, "error: fatal\n", ft_strlen("error: fatal\n"));
exit (1);
}
void ft_msg(char *str, char *com)
{
write(2, str, ft_strlen(str));
write(2, com, ft_strlen(com));
write(2, "\n", 1);
}
void ft_cd(char **argv)
{
int i = 0;
while (argv[i])
i++;
if (i != 2)
write (2, "error: cd: bad arguments\n", ft_strlen("error: cd: bad arguments\n"));
if (chdir(argv[1]))
ft_msg("error: cd: cannot change directory to ", argv[1]);
}
int main(int argc, char **argv, char **env)
{
int j = 1, j_prev, pipes[2], status, type;
char **command;
pid_t pid;
while (j < argc)
{
j_prev = j;
type = 0;
while (j < argc && strcmp(argv[j], "|") && strcmp(argv[j], ";"))
j++;
if (j < argc && !strcmp(argv[j], "|"))
type = 2;
if (j < argc && !strcmp(argv[j], ";"))
type = 1;
argv[j] = 0;
command = &argv[j_prev];
if (type == 2 && pipe(pipes))
ft_error();
pid = fork();
if (pid < 0)
ft_error();
if (pid == 0)
{
if (type == 2)
dup2(pipes[1], 1);
if (!strcmp(command[0], "cd"))
ft_cd(command);
else if (execve(command[0], command, env))
ft_msg("error: cannot execute ", command[0]);
exit (0);
}
else
waitpid(pid, &status, 0);
if (type == 2)
{
dup2(pipes[0], 0);
close(pipes[1]);
close(pipes[0]);
}
if (type == 0)
break;
j++;
}
return (0);
}