-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.c
111 lines (88 loc) · 1.39 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
char **av;
char **make_av(char *);
void print_array(char **av);
int execute(char **command);
int main(void)
{
char *buffer = NULL;
char **command;
size_t bufsize = 0;
while(1)
{
printf("($) ");
getline(&buffer, &bufsize, stdin);
if (strcmp(buffer, "exit\n") == 0)
break;
else
{
command = make_av(buffer);
if (execute(command) == -1)
break;
}
}
free(buffer);
free(av);
return (0);
}
int execute(char **command)
{
pid_t is_kid;
is_kid = fork();
if (is_kid != 0)
{
wait(NULL);
return(0);
}
if (is_kid == 0)
{
if (execve(command[0], command, NULL) == -1)
{
perror("Error: ");
return (-1);
}
}
return (0);
}
char **make_av(char *str)
{
char *buffer = strdup(str);
char *argument;
char prev = '0';
int i = 0, numArgs = 0;
while (buffer[i])
{
if (buffer[i] == ' ' && prev != ' ')
numArgs++;
prev = buffer[i];
i++;
}
av = malloc(sizeof(*av) * (numArgs + 2));
argument = strtok(buffer, " \n");
av[0] = argument;
i = 1;
while (argument != NULL)
{
argument = strtok(NULL, " \n");
av[i] = argument;
i++;
}
av[i] = NULL;
return (av);
}
void print_array(char **array)
{
int i = 0;
while (array[i] != NULL)
{
printf("%s\n", array[i]);
i++;
}
if (array[i] == NULL)
printf("NULL\n");
}