1 |
douglas |
758 |
/* A Simple Shell |
2 |
|
|
* |
3 |
|
|
* Douglas Thrift |
4 |
|
|
*/ |
5 |
|
|
|
6 |
|
|
#include <stdio.h> |
7 |
|
|
#include <stdlib.h> |
8 |
|
|
#include <string.h> |
9 |
|
|
#include <sys/types.h> |
10 |
|
|
#include <unistd.h> |
11 |
|
|
|
12 |
|
|
int main(argc, argv, envp) |
13 |
|
|
int argc; |
14 |
|
|
char **argv, envp; |
15 |
|
|
{ |
16 |
|
|
char command[BUFSIZ] = ""; |
17 |
|
|
|
18 |
|
|
do |
19 |
|
|
{ |
20 |
|
|
/* strtok(3) */ |
21 |
|
|
char *file = strtok(command, " "); |
22 |
|
|
|
23 |
|
|
if (file) |
24 |
|
|
/* strcmp(3) */ |
25 |
|
|
if (strcmp(file, "cd") == 0) |
26 |
|
|
{ |
27 |
|
|
/* strtok */ |
28 |
|
|
char *directory = strtok(NULL, " "); |
29 |
|
|
|
30 |
|
|
if (!directory) |
31 |
|
|
/* getenv(3) */ |
32 |
|
|
directory = getenv("HOME"); |
33 |
|
|
|
34 |
|
|
/* chdir(2) */ |
35 |
|
|
if (chdir(directory) == -1) |
36 |
|
|
/* perror(3) */ |
37 |
|
|
perror(argv[0]); |
38 |
|
|
} |
39 |
|
|
else |
40 |
|
|
{ |
41 |
|
|
unsigned count = 1; |
42 |
|
|
/* malloc(3) */ |
43 |
|
|
char **args = malloc(sizeof (char *) * 2); |
44 |
|
|
pid_t command, value; |
45 |
|
|
|
46 |
|
|
args[0] = file; |
47 |
|
|
|
48 |
|
|
/* strtok(3) */ |
49 |
|
|
while (args[count++] = strtok(NULL, " ")) |
50 |
|
|
/* realloc(3) */ |
51 |
douglas |
760 |
args = realloc(args, sizeof (char *) * (count + 1)); |
52 |
douglas |
758 |
|
53 |
|
|
/* fork(2) */ |
54 |
|
|
switch (command = fork()) |
55 |
|
|
{ |
56 |
|
|
case -1: |
57 |
|
|
/* perror(3) */ |
58 |
|
|
perror(argv[0]); |
59 |
|
|
|
60 |
|
|
return 1; |
61 |
|
|
case 0: |
62 |
|
|
/* execvp(3) */ |
63 |
|
|
execvp(file, args); |
64 |
|
|
/* perror(3) */ |
65 |
|
|
perror(argv[0]); |
66 |
|
|
|
67 |
|
|
return 1; |
68 |
|
|
} |
69 |
|
|
|
70 |
|
|
/* wait(2) */ |
71 |
|
|
while ((value = wait(NULL)) != command) |
72 |
|
|
if (value == -1) |
73 |
|
|
{ |
74 |
|
|
/* perror(3) */ |
75 |
|
|
perror(argv[0]); |
76 |
|
|
|
77 |
|
|
return 1; |
78 |
|
|
} |
79 |
|
|
|
80 |
|
|
/* free(3) */ |
81 |
|
|
free(args); |
82 |
|
|
} |
83 |
|
|
|
84 |
|
|
/* printf(3) */ |
85 |
|
|
printf("$ "); |
86 |
|
|
/* fflush(3) */ |
87 |
|
|
fflush(stdout); |
88 |
|
|
} |
89 |
|
|
/* gets(3) */ |
90 |
|
|
while (gets(command)); |
91 |
|
|
|
92 |
|
|
return 0; |
93 |
|
|
} |