rishtik/src/shellOpt.c

101 lines
2.2 KiB
C
Raw Normal View History

/**
* @file shellOpt.c
* @author rick <rick@gnous.eu>
* @date 2021
*/
#include "parser.h"
#include "essential_shell.h"
2021-02-16 15:12:37 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
/** commands contient lentrée utilisateur parsée avec | :
* ls | wc -l -> [ls, wc -l]
*
* args contient une commande à la fois avec ses arguments séparés
* par les espaces :
* ls -R test -> [ls, -R, test]
*/
char *commands[MAX_LENGTH];
char *args[MAX_LENGTH];
int pid, index = 0, end = 0; /* end permet de savoir quand sarreter */
2021-02-16 15:12:37 +00:00
int my_pipe[2];
2021-02-16 15:12:37 +00:00
if (pipe(my_pipe) == -1)
error(1, FATAL_ERROR, NULL);
2021-02-16 15:12:37 +00:00
for (int i = 0; i < MAX_LENGTH; i++)
{
args[i] = (char *) calloc(MAX_LENGTH, sizeof(char));
commands[i] = (char *) calloc(MAX_LENGTH, sizeof(char));
2021-02-16 15:12:37 +00:00
}
get_command(commands, '|');
2021-02-16 15:12:37 +00:00
while (strcmp(commands[0], "exit"))
2021-02-16 15:12:37 +00:00
{
while (commands[index] != NULL)
2021-02-16 15:12:37 +00:00
{
2021-02-17 09:51:41 +00:00
pid = fork();
if (!pid)
2021-02-16 15:12:37 +00:00
{
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);
2021-02-17 09:51:41 +00:00
return 0;
}
else
{
if (commands[index + 1] == NULL)
2021-02-17 09:51:41 +00:00
{
close(my_pipe[1]);
close(my_pipe[0]);
waitpid(pid, NULL, 0);
}
}
index++;
2021-02-16 15:12:37 +00:00
}
/* remise à 0 des entrées, des commandes, des pipes et de lindex */
2021-02-16 15:12:37 +00:00
for (int i = 0; i < MAX_LENGTH; i++)
{
free(args[i]);
free(commands[i]);
2021-02-16 15:12:37 +00:00
args[i] = (char *) calloc(MAX_LENGTH, sizeof(char));
commands[i] = (char *) calloc(MAX_LENGTH, sizeof(char));
2021-02-16 15:12:37 +00:00
}
get_command(commands, '|');
if (pipe(my_pipe) == -1)
2021-02-17 23:13:25 +00:00
{
for (int i = 0; i < MAX_LENGTH; i++)
{
free(args[i]);
free(commands[i]);
}
error(1, FATAL_ERROR, NULL);
2021-02-17 23:13:25 +00:00
}
2021-02-16 15:12:37 +00:00
index = 0;
}
for (int i = 0; i < MAX_LENGTH; i++)
{
free(commands[i]);
2021-02-16 15:12:37 +00:00
free(args[i]);
}
return 0;
}