crear un simulador de shell
Publicado por rocko (2 intervenciones) el 27/03/2001 20:06:55
alguien sabe como crear un simulador de shell en c
Valora esta pregunta


0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAX_COMMAND_LENGTH 100
#define MAX_ARGS 10
int main() {
char command[MAX_COMMAND_LENGTH];
char* args[MAX_ARGS];
int status;
while (1) {
printf("Shell> ");
fgets(command, sizeof(command), stdin);
// Eliminar el salto de línea final
command[strcspn(command, "\n")] = '\0';
// Dividir el comando en argumentos
char* token = strtok(command, " ");
int i = 0;
while (token != NULL && i < MAX_ARGS - 1) {
args = token;
token = strtok(NULL, " ");
i++;
}
args[i] = NULL;
// Salir del bucle si se ingresa "exit"
if (strcmp(args[0], "exit") == 0) {
break;
}
// Crear un proceso hijo para ejecutar el comando
pid_t pid = fork();
if (pid < 0) {
perror("Error al crear el proceso hijo");
exit(1);
} else if (pid == 0) {
// Proceso hijo
execvp(args[0], args);
perror("Error al ejecutar el comando");
exit(1);
} else {
// Proceso padre
waitpid(pid, &status, 0);
}
}
return 0;
}