-
Notifications
You must be signed in to change notification settings - Fork 1
/
shell.c
97 lines (82 loc) · 2.07 KB
/
shell.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
96
97
#include "shell.h"
extern char **environ;
int main(void)
{
int status;
char *buffer = NULL;
size_t buffer_size = 0;
char *token;
int i = 0;
char **memory;
pid_t child_pid;
int j;
int is_piped_input;
memory = malloc(sizeof(char *) * 1024);
while (1)
{
if (getline(&buffer, &buffer_size, stdin) == -1)
break;
i = 0;
token = strtok(buffer, " \t\n");
if (token == NULL)
continue;
while (token != NULL)
{
memory[i] = malloc(strlen(token) + 1);
strcpy(memory[i], token);
token = strtok(NULL, " \t\n");
i++;
}
memory[i] = NULL;
if (i > 0 && strcmp(memory[0], "exit") == 0)
{
for (j = 0; j < i; j++)
free(memory[j]);
free(buffer);
free(memory);
exit(EXIT_SUCCESS);
}
else if (i > 0 && strcmp(memory[0], "env") == 0)
{
char **env_ptr = environ;
while (*env_ptr != NULL)
{
printf("%s\n", *env_ptr);
env_ptr++;
}
}
else
{
is_piped_input = isatty(fileno(stdin)) == 0;
child_pid = fork();
if (child_pid == 0)
{
if (is_piped_input)
{
if (execvp(memory[0], memory) == -1)
{
perror("ERROR execvp:");
exit(EXIT_FAILURE);
}
}
else
{
if (execlp("/bin/sh", "sh", "-c", buffer, (char *)NULL) == -1)
{
perror("ERROR execlp:");
exit(EXIT_FAILURE);
}
}
}
else
{
wait(&status);
}
}
for (j = 0; j < i; j++)
free(memory[j]);
}
free(buffer);
free(memory);
return 0;
}