72 lines
1.6 KiB
C
72 lines
1.6 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;
|
||
|
|
||
|
int main(int argc, char *argv[])
|
||
|
{
|
||
|
// loop principal
|
||
|
while (1)
|
||
|
{
|
||
|
printf(">>> ");
|
||
|
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;
|
||
|
}
|
||
|
|
||
|
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;
|
||
|
}
|