Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <sys/wait.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/types.h>
- #include <assert.h>
- #include <signal.h> //for kill
- #include <fcntl.h>
- void execute(char **argv)
- {
- int status;
- int pid = fork();
- if (pid <0) //fork error has happened
- {
- perror("Can't fork a child process\n");
- exit(EXIT_FAILURE);
- }
- if (pid==0) //It's the child process and can run his task
- {
- execvp(argv[0],argv);
- perror("error");
- }
- else //pid>0 it's the parent and should wait for the child
- {
- int status;
- // int wc = wait(&status);
- // assert(wc != -1);
- //while(wait(&status)!=pid)
- // ;
- wait(NULL); //the way taught in the class
- }
- }
- int main (int argc, char **argv)
- { char cwd[100];
- char input[512];
- char *args[512];
- char **next = args;
- char *temp;
- getcwd(cwd,sizeof(cwd));
- while (1)
- {
- chdir(cwd);
- printf("mysh> ");
- fgets(input,512,stdin);
- input[strlen(input) - 1] = 0;
- temp = strtok(input, " ");
- while(temp != NULL)
- {
- //printf("%s\n", temp);
- *next++ = temp;
- temp = strtok(NULL, " ");
- }
- *next = NULL;
- next=args;
- ///////////////////////////////////
- int i;
- for (i=1; args[i];i++)
- {
- if (strcmp(args[i],">")==0)
- {
- printf("argv[i] %s %d \n", args[i], i);
- int out = open(args[i+1], O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
- close(1);
- int fdl=dup2(out,1);
- close(out);
- execvp(args[0],args);
- // open(STDOUT, ">>", \$out);
- }
- }
- ////////////////////////////
- if (strcmp(args[0], "exit")==0)
- // exit(EXIT_SUCCESS);
- exit(0);
- if (strcmp(args[0], "cd")==0)
- {
- printf("argv[1] is %s \n", args[1]);
- if ((!args[1]) || (strcmp(args[1],"~")==0))
- {
- chdir(getenv("HOME"));
- getcwd(cwd,sizeof(cwd));
- }
- else
- {
- chdir(args[1]);
- getcwd(cwd,sizeof(cwd));
- }
- }
- else
- {
- execute(args);
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement