-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfase4.c
More file actions
248 lines (226 loc) · 6.66 KB
/
fase4.c
File metadata and controls
248 lines (226 loc) · 6.66 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
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/**
* Fase 4 - Práctica 2
* Sistemas Operativos 1
* Autores: Luis Arjona y Hector Santos
*/
#include "fase4.h"
/*
* Contamos los elementos que contiene args
*/
int contar_elementos(char **args) {
int nargs;
nargs = 0;
while (args[nargs] != NULL) {
nargs++;
}
return nargs;
}
/*
* Imprimir error en color rojo y por la salida de errores
*/
void imprimir_error(char *error_msg) {
if (error_msg == NULL) {
fprintf(stderr, ANSI_COLOR_RED"Error %d: %s\n", errno, strerror(errno));
printf(ANSI_COLOR_RESET);
} else{
fprintf(stderr, ANSI_COLOR_RED"%s\n", error_msg);
printf(ANSI_COLOR_RESET);
}
}
/*
* Simulación de la ejecución del comando 'cd'
*/
int internal_cd(char **args) {
char path_actual[256];
int nargs;
nargs = contar_elementos(args);
if ( nargs > 2) imprimir_error("Error de sintaxis. Uso: <cd dir_path>");
else{
int succes;
char *ptr_path;
if (nargs == 1) succes = chdir(getenv("HOME")); // cd sin argumentos, vamos a $HOME
else succes = chdir(args[1]); // si existe el directorio pasado como argumento, succes = 0
if (succes != 0) imprimir_error(NULL);
else {
ptr_path = getcwd(path_actual, sizeof(path_actual));
if (ptr_path == NULL) imprimir_error(NULL);
else {
printf(ANSI_COLOR_GREEN "Nuevo directorio actual: %s\n", ptr_path);
printf(ANSI_COLOR_RESET);
}
}
}
return 1;
}
/*
* Exportamos el valor de las variables de entorno del minishell
*/
int internal_export(char **args) {
char *text,*nombre,*valor;
text = NULL;
if(args[1]!=NULL){ // Si después del export hay algo más
//args[1]= NOMBRE=VALOR;
text=args[1];
const char *separador= "=";
char *token;
token =strtok(text,separador);
nombre=token; // Extraemos nombre
token = strtok(NULL,separador);
valor=token; // Extraemos valor
}
if (args[1] == NULL || valor==NULL||nombre==NULL){ // error
imprimir_error("Error de sintaxis. Uso: export Nombre=Valor");
}else{ // todo correcto
printf(ANSI_COLOR_GREEN "nombre: %s\nvalor:%s\n",nombre,valor);
printf("antiguo valor de %s es %s\n",nombre,getenv(nombre));
setenv(nombre,valor,1);
printf("ahora valor de %s= %s\n",nombre,getenv(nombre));
printf(ANSI_COLOR_RESET);
}
return 1;
}
int internal_source(char **args) {
FILE *fp;
fp = fopen(args[1], "r");
if (fp == NULL) {
imprimir_error(NULL);
} else {
char linea[LINEA];
while (fgets(linea, LINEA, fp) != NULL) {
execute_line(linea);
}
fclose(fp);
}
return 1;
}
int internal_jobs(char **args) {
printf("%s\n", "Comando jobs");
return 1;
}
int check_internal(char **args) {
if (args[0] == 0) {
return -1;
} else {
if (strcmp(args[0], "cd") == 0) {
return internal_cd(args);
} else if (strcmp(args[0], "export") == 0) {
return internal_export(args);
} else if (strcmp(args[0], "source") == 0) {
return internal_source(args);
} else if (strcmp(args[0], "jobs") == 0) {
return internal_jobs(args);
} else if (strcmp(args[0], "exit") == 0) {
exit(0);
} else {
return 0;
}
}
}
/*
* El contenido de 'line' es troceado, es decir cada palabra separada por espacios, saltos de línea o tabulaciones es insertada en el array 'args'
*/
int parse_args(char **args, char *line) {
char lineaux[LINEA];
strcpy(lineaux, line);
int i = 0;
char *token;
token = strtok(lineaux, " \n\r");
while (token != 0) {
args[i] = token;
if (strncmp(args[i],"#",1) == 0) { // Si no es un comentario lo añadimos como argumento
break;
}
i++;
token = strtok(NULL, " \n\r"); // Ponemos NULL para no sobrescribir la 'line'
}
args[i] = 0; //Null al final, ya que no habra nada mas que trocear
strtok(line, "\n\r");
return i;
}
void reaper(int signum) {
signal(SIGCHLD, reaper);
pid_t ended;
int status;
while ((ended = waitpid(-1, &status, WNOHANG)) > 0) {
if (jobs_list[0].pid == ended) {
jobs_list[0].pid = 0;
jobs_list[0].status = 'F';
switch (status) {
case 0:
printf("[reaper()→ Proceso hijo %d finalizado con exit code: %d]\n",
ended, status);
break;
case 2:
printf("[reaper()→ Proceso hijo %d finalizado por señal: %d]\n",
ended, status);
break;
}
}
}
}
int execute_line(char *line) {
char *args[LINEA];
parse_args(args, line);
if (check_internal(args) == 0) {
pid_t pid;
pid = fork();
jobs_list[0].pid = pid;
jobs_list[0].status = 'E';
strcpy(jobs_list[0].command_line, line);
printf("jobs_list[0].command_line: %s\n", jobs_list[0].command_line);
if (pid == -1) {
imprimir_error(NULL);
exit(0);
} else if (pid == 0) {
signal(SIGINT, SIG_DFL);
signal(SIGCHLD, SIG_DFL);
printf("[execute_line()→ PID padre: %d]\n", getppid());
printf("[execute_line()→ PID hijo: %d]\n", getpid());
if (execvp(args[0], args) < 0) {
fprintf(stderr, ANSI_COLOR_RED"%s", args[0]);
imprimir_error(": no se encontró la orden");
exit(0);
}
} else {
while (jobs_list[0].pid != 0) {
pause();
}
}
}
return 0;
}
void ctrlc(int signum) {
signal(SIGINT, ctrlc);
printf("\n[ctrlc()→ Soy el proceso con PID %d, el proceso en foreground es %d "
"(%s)]\n", getpid(), jobs_list[0].pid, jobs_list[0].command_line);
if (jobs_list[0].pid > 0) {
printf("[ctrlc()→ Señal 2 enviada a %d (%s) por %d]\n", jobs_list[0].pid,
jobs_list[0].command_line, getpid());
kill(jobs_list[0].pid, SIGINT);
} else printf("[ctrlc()→ Señal 2 no enviada por %d debido a que no hay "
"proceso en foreground]\n", getpid());
}
char *read_line(char *line) {
char *ptr_line;
printf(ANSI_COLOR_BLUE"%s %s", getenv("USER"), PROMPT);
printf(ANSI_COLOR_RESET);
ptr_line = fgets(line, LINEA, stdin);
if (ptr_line == NULL && !feof(stdin)) {
// line = ptr_line;
// strcpy(ptr_line, "NULL");
ptr_line = line;
ptr_line[0] = 0;
}
fflush(stdin); // liberamos la entrada estandar
return ptr_line;
}
int main(int argc, char const *argv[]) {
// Asignamos dichas señales a las funciones que las van a manejar
signal(SIGCHLD, reaper);
signal(SIGINT, ctrlc);
char line[LINEA];
while (read_line(line)) {
execute_line(line);
}
return 0;
}