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
| # include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
# include <sys/types.h>
# include <sys/wait.h>
# include <assert.h>
# include <string.h>
enum {
MaxLigne = 1024, // longueur max d'une ligne de commandes
MaxMot = MaxLigne / 2, // nbre max de mot dans la ligne
MaxDirs = 100, // nbre max de repertoire dans PATH
MaxPathLength = 512, // longueur max d'un nom de fichier
};
void decouper(char *, char *, char **, int);
# define PROMPT "? "
int
main(int argc, char * argv[]){
char ligne[MaxLigne];
char pathname[MaxPathLength];
char * mot[MaxMot];
char * dirs[MaxDirs];
int i, tmp;
decouper(strdup(getenv("PATH")), ":", dirs, MaxDirs);
for(printf(PROMPT); fgets(ligne, sizeof ligne, stdin) != 0; printf(PROMPT)){
decouper(ligne, " \t\n", mot, MaxMot);
if (mot[0] == 0) // ligne vide
continue;
tmp = fork(); // lancer le processus enfant
if (tmp < 0){
perror("fork");
continue;
}
if (tmp != 0){ // parent : attendre la fin de l'enfant
while(wait(0) != tmp)
;
continue;
}
// enfant : exec du programme
for(i = 0; dirs[i] != 0; i++){
snprintf(pathname, sizeof pathname, "%s/%s", dirs[i], mot[0]);
execv(pathname, mot);
}
// aucun exec n'a fonctionne
fprintf(stderr, "%s: not found\n", mot[0]);
exit(1);
}
printf("Bye\n");
return 0;
} |