-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhsh.c
108 lines (103 loc) · 1.76 KB
/
hsh.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
#include "hsh.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
/**
* handler - handle system signals
*
* @no: signal number
*/
void handler(int no)
{
(void)no;
if (isatty(fileno(stdin)))
{
_puts("\n#cisfun$ ");
fflush(stdout);
}
}
/**
* evaluate - evaluate input
*
* @ctx: shell context
*
* Return: exit value
*/
int evaluate(context_t *ctx)
{
char op, *line = ctx->buf.ptr;
int i, exit = 0;
command_t *cmd = NULL;
(ctx->line)++;
parse_commands(ctx, strtok(line, "\n"));
while (ctx->cmd)
{
parse_args(ctx);
if (exec_builtin(ctx) == -1 && ctx->cmd != NULL)
{
i = execute(ctx);
if (i == 1)
{
ctx->status = 127;
print_err(ctx, "not found\n");
}
else if (i == -1)
exit = 1;
}
cmd = next_command(&ctx->cmd);
op = cmd->op;
free_commands(&cmd);
if (op == OP_AND && ctx->status)
break;
}
return (exit);
}
/**
* main - entry point for simple shell
*
* @ac: argument count
* @av: arguments array
*
* Return: 0 on success, non-zero on failure
*/
int main(int ac, char *av[])
{
int if_exit = 0, fd = 0;
context_t ctx = { NULL, 0, NULL, NULL, NULL, { NULL, 0 }, 0, 0};
FILE *stream;
ctx.name = av[0];
if (ac >= 2)
{
fd = open(av[1], O_RDONLY);
if (fd < 0)
{
print_err(&ctx, "Can't open ");
puts_err(av[1]);
putchar_err('\n');
exit(127);
}
stream = fdopen(fd, "r");
}
else
stream = stdin;
signal(SIGINT, &handler);
allocate_env(&ctx);
do {
free_buf(&ctx.buf);
if (prompt(&ctx, stream) == EOF)
{
if (ctx.isatty)
_puts("\n");
if_exit = 1;
}
else if (ctx.buf.ptr != NULL)
if_exit = evaluate(&ctx);
} while (!if_exit);
free_ctx(&ctx);
fclose(stream);
return (ctx.status);
}