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
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
char** parsing(char * str, int x)
{
int cpt=0;
char ** tab = NULL;
char *pch = strtok(str, " ");
tab = malloc(1024 * sizeof(char*));
while(pch != NULL)
{
if(cpt >= x)
{
tab[cpt-x] = malloc (1024);
strcpy(tab[cpt-x], pch);
tab[cpt-x] = pch;
}
cpt++;
pch = strtok (NULL, " ");
}
free(pch);
return tab;
}
int comptemot(char * str)
{
int i=0;
int nbmot=1;
int sizemot = strlen(str);
for(i = 0 ; i < sizemot; i++)
{
if(str[i] == ' ')
nbmot++;
}
return nbmot;
}
// On vérifie si la commande se situe dans "/bin/", sinon elle est dans "/usr/bin/"
int verify_cmd(char * cmd)
{
struct dirent *dirlist;
DIR *rep;
rep = opendir("/bin/");
while ((dirlist = readdir(rep)))
{
if( dirlist->d_type == DT_REG)
{
if(strcmp(dirlist->d_name, cmd) == 0)
{
return 1;
}
}
}
closedir(rep);
return 0;
}
void exec_cmd(char *cmd, char** arg)
{
pid_t pid;
int status;
char *bin=NULL;
bin = malloc( 1024 );
if(verify_cmd(cmd) == 1)
{
strcpy(bin, "/bin/");
}
else
{
strcpy(bin, "/usr/bin");
}
strcat(bin, cmd);
printf("arg : %s\n", arg[0]);
pid = fork();
switch(pid)
{
case -1 : perror("problem fork"); break;
case 0: execv(bin, arg);break;
default : waitpid(pid, &status, 0);
}
free(bin);
}
int main()
{
char** ligne = NULL;
char ** cmd = calloc(1024,1);
char chx_user[512];
char bis[512];
int size;
while(1)
{
if (fgets(chx_user, 512, stdin) != NULL)
{
size = comptemot(chx_user);
printf("size %d\n", size);
strcpy(bis, chx_user);
ligne = parsing(chx_user, 0);
cmd = parsing(bis, 1);
exec_cmd(ligne[0], cmd);
cmd=memset(cmd, '\0', 1024);
free(ligne);
}
}
} |
Partager