-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.c
131 lines (112 loc) · 2.17 KB
/
shell.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
#include "shell.h"
/**
* handle_signal - handle signals
* @sigint: signal number
*/
void handle_signal(int sigint)
{
prompt(sigint);
if (sigint == 2)
{
errno = 130;
}
}
/**
* main - Entry point
* @argc: argument count
* @argv: argument vector
*
* Return: 0 success
*/
int main(int argc, char **argv)
{
signal(SIGINT, handle_signal);
if (argc > 1)
{
exit(execute_commands_from_file(argv));
}
while (prompt(0))
{
argc = get_argv(&argv);
if (argc > 0)
{
argv[argc] = NULL;
run_command(argv);
free_argv(argv);
}
}
return (0);
}
/**
* exit_with_error - writes message to stderr and exits with error code
* @code: error code
* @shell: shell program
* @filename: file name
*/
void exit_with_error(int code, char *shell, const char *filename)
{
dprintf(STDERR_FILENO, "%s: 0: Can't open %s\n", shell, filename);
exit(code);
}
/**
* execute_commands_from_file - Execute commands from a file
* @argv: argument vector
*
* Description: Reads commands from the specified file and executes them
*
* Return: 0 if successful, -1 on error
*
*/
int execute_commands_from_file(char **argv)
{
char command[1000];
int fd;
ssize_t bytes_read;
if (access(argv[1], R_OK) != 0)
exit_with_error(127, argv[0], argv[1]);
fd = open(argv[1], O_RDONLY);
if (fd == -1)
{
perror((char *)EACCES);
exit(127);
}
while ((bytes_read = read(fd, command, sizeof(command))) > 0)
{
pid_t child_p = fork();
if (child_p == -1)
{
perror("Error creating process");
return (1);
}
if (child_p == 0)
{
char *args[] = {"/bin/sh", "-c", NULL, NULL};
command[bytes_read] = '\0';
args[2] = command;
if (execve(args[0], args, environ) == -1)
{
perror("execve error");
}
}
}
close(fd), exit(0);
return (0);
}
/**
* run_command - this function is responsible for
* directing the flow of execution
* @argv: argument vector
*
* Return: 0 if succesful and -1 if unsuccessful
*/
int run_command(char **argv)
{
get_builtin execute_builtin;
int run_status;
execute_builtin = handle_builtin_func(argv[0]);
if (execute_builtin)
run_status = execute_builtin(argv);
else
run_status = execute_command(argv);
return (run_status);
}