Ajout commande cd, close #4

This commit is contained in:
rick 2021-02-18 17:20:46 +01:00
parent 882bba6150
commit b507e1ef82
Signed by: Rick
GPG Key ID: 2B593F087240EE99
3 changed files with 57 additions and 20 deletions

View File

@ -8,6 +8,8 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/**
* error(): gère les erreurs selon leur code et leur type
@ -17,6 +19,7 @@
* @message: message à afficher pour + dinfos ou erreur non implémentée
*
* 1 erreur lors de la création des pipes
* 2 chemin inexistant (pour cd)
*/
void error(int code, int type, char *message)
{
@ -25,6 +28,9 @@ void error(int code, int type, char *message)
case 1:
printf("Erreur lors de la création des pipes.\n");
break;
case 2:
printf("Chemin inexistant.\n");
break;
default:
if (message == NULL)
@ -39,3 +45,24 @@ void error(int code, int type, char *message)
if (type == FATAL_ERROR)
exit(code);
}
/**
* change_dir(): fonction pour vérifier si la commande est un cd
* @args: la liste des arguments de la commade
*
* Return: 0 si ce nest pas un cd, 1 sinon
*/
int change_dir(char *args[])
{
int ret = 0; /* 1 si cd */
if (!strncmp(args[0], "cd", 2))
{
ret = 1;
if (chdir(args[1]))
error(2, NON_FATAL_ERROR, "Un nom de fichier au lieu dun dossier \
a pu etre passé en paramètres.");
}
return ret;
}

View File

@ -15,5 +15,6 @@
#define NON_FATAL_ERROR 0
void error(int code, int type, char *message);
int change_dir(char *args[]);
#endif

View File

@ -43,30 +43,39 @@ int main()
{
while (commands[index] != NULL)
{
pid = fork();
if (!pid)
parse_string(commands[index], args, ' ');
if (!change_dir(args))
{
parse_string(commands[index], args, ' ');
if (commands[index+1] == NULL)
dup2(my_pipe[0], STDIN_FILENO);
else if (index == 0)
dup2(my_pipe[1], STDOUT_FILENO);
close(my_pipe[0]);
close(my_pipe[1]);
execvp(args[0], args);
return 0;
}
else
{
if (commands[index + 1] == NULL)
pid = fork();
if (!pid)
{
close(my_pipe[1]);
close(my_pipe[0]);
waitpid(pid, NULL, 0);
if (commands[index+1] == NULL)
dup2(my_pipe[0], STDIN_FILENO);
else if (index == 0)
dup2(my_pipe[1], STDOUT_FILENO);
close(my_pipe[0]);
close(my_pipe[1]);
execvp(args[0], args);
return 0;
}
else
{
if (commands[index + 1] == NULL)
{
close(my_pipe[1]);
close(my_pipe[0]);
waitpid(pid, NULL, 0);
}
}
}
index++;
for (int i = 0; i < MAX_LENGTH; i++)
{
free(args[i]);
args[i] = (char *) calloc(MAX_LENGTH, sizeof(char));
}
index++;
}
/* remise à 0 des entrées, des commandes, des pipes et de lindex */