projet-systeme-exploitation.../Q4.c
2021-04-24 17:32:54 +02:00

94 lines
2.2 KiB
C

#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <setjmp.h>
#include "readcmd.h"
extern int errno;
struct cmdline *cmd;
int pid_fils;
char initcd[256], currentcd[256];
int main(int argc, char *argv[])
{
getcwd(initcd, sizeof(initcd));
// loop principal
while (1)
{
getcwd(currentcd, sizeof(currentcd));
printf("%s >>> ", currentcd);
cmd = readcmd();
if (cmd == NULL)
{ // EOF
break;
}
else if (cmd->seq[0] == NULL)
{ // empty
continue;
}
else if (!strcmp(cmd->seq[0][0], "exit"))
{ // "exit"
break;
}
else if (!strcmp(cmd->seq[0][0], "cd"))
{ // "cd"
int ret = 0;
if (cmd->seq[0][1] == NULL)
{ // no path
ret = chdir(initcd);
}
else
{ // with path
ret = chdir(cmd->seq[0][1]);
}
if (ret)
{ // wrong path
fprintf(stderr, "ERROR: cd failed, (%d) %s\n", errno, strerror(errno));
}
continue;
}
pid_fils = fork();
if (pid_fils == -1)
{ // fork fail ?
fprintf(stderr, "ERROR: forking failed, (%d) %s\n", errno, strerror(errno));
exit(errno);
}
if (pid_fils == 0)
{ // instructions du fils
execvp(cmd->seq[0][0], cmd->seq[0]);
exit(errno); // si execlp échoue on exit avec une erreur
}
else
{ // instructions du père
int wait_code;
pid_t id = waitpid(pid_fils, &wait_code, 0); // on attend la fin de l'exec du fils
if (id == -1)
{ // wait fail ?
fprintf(stderr, "ERROR: waiting for %d failed, (%d) %s\n", wait_code, errno, strerror(errno));
exit(errno);
}
if (wait_code)
{ // execvp fail ?
fprintf(stderr, "ERROR: %d's execution failed, (%d) %s\n", pid_fils, wait_code, strerror(wait_code));
}
}
}
return EXIT_SUCCESS;
}