#include #include #include #include #include #define MAX_ARGS 5 #define MAX_LEN 100 #define PROMPT "$ " void eco(int argcount, char *args[]) { int i; for(i = 0; i < argcount; i++) { printf("%s ", args[i]); } printf("\n"); } void runcommand(char *args[], int background) { int pid = fork(); // filho if(pid == 0) { if(execvp(args[0], args) == -1) { perror(args[0]); exit(0); } } // pai else { if(!background) waitpid(pid, NULL, 0); } } int main(int argc, char *argv[]) { char str_buf[MAX_LEN]; char *args[MAX_ARGS]; while(1) { printf(PROMPT); fgets(str_buf, MAX_LEN, stdin); int argcount = 0; int background = 0; char *p; p = strtok(str_buf, " \n"); int i = 0; DIR *d; struct dirent *dp; /* Separa a string e constrói array de argumentos e expande os wildcards */ while(p != NULL) { if(p[0] != '*') { // se não for wildcard args[i] = p; argcount++; i++; } else { // se for wildcard d = opendir("."); /* percorre todos os ficheiros da directoria */ while((dp = readdir(d)) != NULL) { if(strcmp(dp->d_name, p) == 0) { // a função não faz o esperado, deveria verificar se o nome ficheiro pode ser dado pela wildcard args[i] = dp->d_name; argcount++; i++; } } closedir(d); } p = strtok(NULL, " \n"); } /* Se for para correr em background, remover a última string */ if(strcmp(args[i-1], "&") == 0) { argcount--; i--; background = 1; } args[i++] = NULL; /* Comandos internos */ if(args[0] == NULL) { printf("Erro: linha vazia\n"); } else if(strcmp(args[0], "exit") == 0) { exit(0); } else if(strcmp(args[0], "cd") == 0) { if(argcount > 1) { /* Se ocorrer um erro */ if(chdir(args[1]) == -1) { printf("Ocorreu um erro."); } } else { char buf[MAX_LEN]; getcwd(buf, MAX_LEN); printf("%s\n", buf); } } else if(strcmp(args[0], "eco") == 0) { eco(argcount - 1, &args[1]); } else { runcommand(args, background); } } }