Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #define MAX_LENGTH 1024
- #define DELIMS " \t\r\n"
- int main(int argc, char *argv[]) {
- call_func(stdin);
- return 0;
- }
- void call_func(FILE *stream) {
- char *cmd;
- char *line;
- char cwd[MAX_LENGTH];
- char** commands;
- char commands_args[MAX_LENGTH];
- while(1) {
- errno = 0;
- if (getcwd(cwd, sizeof(cwd)) != NULL) {
- fprintf(stdout, "%s $ ", cwd);
- }
- else {
- perror("getcwd() error");
- }
- line = malloc(100 * sizeof(char));
- if (!fgets(line, MAX_LENGTH, stream)) {
- break;
- }
- line = strtok(line, "\n");
- commands = (char**)malloc(50 * sizeof(char*));
- for (int i = 0; i < 50; i++) {
- commands[i] = (char*)malloc(50 * sizeof(char));
- }
- if((commands[0] = strtok(line, "|"))) {
- int i = 1;
- while(1) {
- commands[i] = strtok(0, "|");
- if(commands[i] == NULL) {
- break;
- }
- }
- if((cmd = strtok(commands[0], " "))) {
- if (strcmp(cmd, "cd") == 0) {
- char *arg = strtok(0, DELIMS);
- if (!arg) {
- fprintf(stderr, "cd missing argument.\n");
- }
- else {
- chdir(arg);
- }
- }
- else if (strcmp(cmd, "exit") == 0) {
- break;
- }
- else if (strcmp(cmd, ".") == 0) {
- char *arg = strtok(0, DELIMS);
- FILE * pFile;
- pFile = fopen (arg,"r");
- call_func(pFile);
- }
- else if (cmd == NULL) {
- system(line);
- }
- else {
- int pfds[2];
- pipe(pfds);
- int id = fork();
- if(id == 0) {
- dup2(pfds[1], 1);
- close(pfds[0]);
- char* argb[20];
- argb[0] = cmd;
- argb[1] = strtok(0, DELIMS);
- argb[2] = NULL;
- execvp(argb[0], argb);
- exit(o);
- }
- else {
- int id_2 = fork();
- if(id_2 == 0) {
- dup2(pfds[0], 0);
- close(pfds[1]);
- wait(&id);
- char* argb[20];
- argb[0] = "grep";
- argb[1] = "c";
- argb[2] = NULL;
- execvp(argb[0], argb);
- exit(o);
- }
- else {
- wait(&id);
- wait(&id_2);
- printf("done");
- }
- }
- }
- if (errno) {
- perror("Command failed");
- }
- }
- }
- }
- }
- //Gemaakt door Joeri van Vuuren en Gijs Schrijver
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement