-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell-0.1.6.c
135 lines (116 loc) · 1.9 KB
/
shell-0.1.6.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
int get_argc (const char *cmdline)
{
int i = 0;
int argc = 1;
for(i = 0;cmdline[i] != '\0';i++)
{
if((cmdline[i] == ' ') || (cmdline[i] == '\n'))
argc++;
}
argc = argc + 2;
return argc;
}
int * get_sizes (const char *cmdline)
{
int i, j, c;
i = j = c = 0;
int n = get_argc(cmdline);
int *sizetable = malloc(n * sizeof(int *));
for(i = 0;cmdline[i] != '\0';i++)
{
if((cmdline[i] == ' ') || (cmdline[i] == '\n'))
{
sizetable[c] = j;
if(cmdline[i] != '\n')
{
c++;
j = 0;
}
}
else
j++;
}
sizetable[c + 1] = 1;
return sizetable;
}
char **allocate_argv(const char *cmdline)
{
int rows = get_argc(cmdline);
int *sizes = get_sizes(cmdline);
char **argv = malloc(rows * sizeof(char *));
int i = 0;
for(i = 0;i < rows;i++)
argv[i] = malloc(sizes[i] * sizeof(char *));
free(sizes);
return argv;
}
char **parse_cmdline (const char *cmdline)
{
int i, j, c;
i = j = c = 0;
char **args = allocate_argv(cmdline);
for(i = 0;cmdline[i] != '\0';i++)
{
if((cmdline[i] == ' ') || (cmdline[i] == '\n'))
{
args[c][j] = '\0';
if(cmdline[i] != '\n')
{
c++;
j = 0;
}
}
else
{
args[c][j] = cmdline[i];
j++;
}
}
args[c + 1][0] = '\0';
return args;
}
void exec (char **args)
{
int status, exec_return;
pid_t pid = fork();
if (pid == 0)
{
exec_return = execv(args[0], args);
if(exec_return == - 1)
perror(args[0]);
}
else if (pid > 0)
{
pid = waitpid(pid, &status, 0);
if(pid == -1)
{
perror("waitpid");
exit(1);
}
}
else
{
perror("fork");
exit(1);
}
}
int main(void)
{
char *line = NULL;
size_t len = 0;
ssize_t read;
char **args;
while((read = getline(&line, &len, stdin)) != -1)
{
args = parse_cmdline(line);
exec(args);
}
free(line);
free(args);
return 0;
}