/
frontend.c
91 lines (72 loc) · 2.01 KB
/
frontend.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
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "io.h"
#include "shell_token_list.h"
#include "cmdline.h"
#include "command.h"
#include "shell_parser.h"
#include "std_wrappers.h"
#include "builtin.h"
#define BUFFER_SIZE 1024
static int run_foreground_command(CmdCmpList list);
void run_shell(void)
{
char input[BUFFER_SIZE];
while (true) {
if ( !get_input_line(input, BUFFER_SIZE) ) {
putchar('\n');
break;
}
if ( !strcmp(input, "exit") ) {
break;
}
TokenList tlist = parse_input(input);
CmdCmpList clist = cmdline_create(tlist);
token_list_destroy(tlist);
if ( !cmdline_is_valid(clist) ) {
printf("pgshell: syntax error\n");
}
else {
run_foreground_command(clist);
}
cmdline_destroy(clist);
}
printf("Goodbye!\n");
}
static int run_foreground_command(CmdCmpList list)
{
Command cmd = cmdline_component_at_index(list, 0)->content.cmd;
if ( !execute_builtin(cmd) ) {
const pid_t pid = xfork();
if ( pid == 0 ) {
char ** args = command_raw_args(cmd);
execvp(args[0], args);
switch ( errno ) {
case EACCES:
fprintf(stderr, "pgshell: %s: Permission denied\n",
args[0]);
break;
case ENOENT:
fprintf(stderr, "pgshell: %s: No such file or directory\n",
args[0]);
break;
default:
fprintf(stderr, "pgshell: other exec() error\n");
break;
}
cmdline_destroy(list);
exit(EXIT_FAILURE);
}
int status;
waitpid(pid, &status, 0);
return status;
}
return 0;
}