-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.c
More file actions
73 lines (62 loc) · 1.33 KB
/
shell.c
File metadata and controls
73 lines (62 loc) · 1.33 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
//Returns an array of tokens
char** tokenize(char* input)
{
char** tokens = malloc(sizeof(char*) * (51));
char* oneToken;
//sorts input into tokens, adds NULL pointer to the end
int i = 0;
while(input != NULL)
{
oneToken = strsep(&input, "\n");
if(oneToken[0] == '\0')
{
break;
}
tokens[i] = oneToken;
i++;
}
tokens[i] = NULL;
return tokens;
}
//Runs the command entered into the shell
void runCommand(char** tokens)
{
const char* command = tokens[0];
int pid;
pid = fork();
if(pid == 0)
{
//Child process
execvp(command, tokens);
}
else
{
//Parent process
wait(NULL);
}
}
int main(int argc, char* argv[])
{
char command[50];
//runs the shell until the user kills the process
while(!feof(stdin))
{
printf("$> ");
fgets(command, 50, stdin);
//Checks to make sure a blank line isn't inputted
while(command[0] == '\n')
{
printf("$> ");
fgets(command, 50, stdin);
}
char** allTokens = tokenize(command);
runCommand(allTokens);
free(allTokens);
}
return 0;
}