99 lines
1.6 KiB
C
99 lines
1.6 KiB
C
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
#include <unistd.h>
|
|
#include <string.h>
|
|
#include <sys/types.h>
|
|
#include <sys/wait.h>
|
|
|
|
#define MAXARGS 128
|
|
#define MAXLINE 80
|
|
#define FOREVER while(1)
|
|
|
|
extern char **environ;
|
|
|
|
void eval(char *cmdline);
|
|
int parseline(char *buf, char **argv);
|
|
int builtin_cmd(char **argv);
|
|
|
|
int main() {
|
|
char cmdline[MAXLINE];
|
|
|
|
FOREVER {
|
|
printf("> ");
|
|
fgets(cmdline, MAXLINE, stdin);
|
|
if (feof(stdin)) exit(0);
|
|
|
|
eval(cmdline);
|
|
}
|
|
return EXIT_SUCCESS;
|
|
}
|
|
|
|
|
|
void eval(char *cmdline) {
|
|
char *argv[MAXARGS];
|
|
char buf[MAXLINE];
|
|
int bg;
|
|
pid_t pid;
|
|
|
|
strcpy(buf, cmdline);
|
|
bg = parseline(buf, argv);
|
|
if (argv[0] == NULL) {
|
|
return;
|
|
}
|
|
|
|
if (!builtin_cmd(argv)) {
|
|
if ((pid = fork()) == 0) {
|
|
if (execvp(argv[0], argv) < 0) {
|
|
printf("%s: cette commande n'existe pas.\n", argv[0]);
|
|
exit(0);
|
|
}
|
|
}
|
|
|
|
if (!bg) {
|
|
int status;
|
|
if (waitpid(pid, &status, 0) < 0) {
|
|
perror("waitfg: waitpid error"); exit(0);
|
|
}
|
|
}
|
|
else {
|
|
printf("%d %s", pid, cmdline);
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
|
|
int builtin_cmd(char **argv) {
|
|
if (!strcmp(argv[0], "quit"))
|
|
exit(0);
|
|
if (!strcmp(argv[0], "&"))
|
|
return 1;
|
|
return 0;
|
|
}
|
|
|
|
int parseline(char *buf, char **argv) {
|
|
char *delim;
|
|
int argc;
|
|
int bg;
|
|
|
|
buf[strlen(buf)-1] = ' ';
|
|
while (*buf && (*buf == ' ')) {
|
|
buf++;
|
|
}
|
|
|
|
argc = 0;
|
|
while ((delim = strchr(buf, ' '))) {
|
|
argv[argc++] = buf;
|
|
*delim = '\0';
|
|
buf = delim+1;
|
|
while (*buf && (*buf == ' ')) buf++;
|
|
}
|
|
argv[argc] = NULL;
|
|
|
|
if (argc == 0) return 1;
|
|
|
|
if ((bg = (*argv[argc-1] == '&')) != 0) {
|
|
argv[--argc] = NULL;
|
|
}
|
|
|
|
return bg;
|
|
} |