Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Kevin Brough
- //UNIX Shell
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <dirent.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/wait.h>
- void parse(char *line, char *argv[]){ //we'll go through and parse our command line
- argv[0] = strtok(line, " ()|&;\t\n");
- int i;
- for(i = 1; i < 19; i = i++) {
- argv[i] = strtok(NULL, " ()|&;\t\n");
- if (argv[i] == NULL){
- break;
- }
- }
- argv[19] = NULL;//making sure to set the end to null
- }
- int main(void){
- char buffer[100];
- int argc;
- char *argv[20];
- int status, pid;
- int redirectOut, redirectIn, appendOut;
- while(1){
- redirectOut = redirectIn = appendOut = 0;//resetting the booleans for cleanliness
- printf("> ");
- fgets(buffer, 100, stdin);
- parse(buffer, argv);
- if ((strcmp("exit", argv[0])) == 0){//first two built in functions
- exit(0);
- }
- else if(!strcmp("cd", argv[0])){
- if(chdir(argv[1]) != 0) {
- printf("Cannot change dir\n");
- }
- }
- else{
- for (argc=1; argv[argc] != 0; argc++){//checking the commandline arguments to see if there's redirection etc.
- if (!strcmp(argv[argc], ">>")){//the checking
- appendOut = 1;//making sure we set the boolean value
- argv[argc] = 0;//saving the args then breaking out
- break;
- }
- else if(!strcmp(argv[argc], ">")){
- redirectOut = 1;
- argv[argc] = 0;
- break;
- }
- else if(!strcmp(argv[argc], "<")){
- redirectIn = 1;
- argv[argc] = 0;
- break;
- }
- }
- pid = fork();
- if (pid == 0){//child process
- if (appendOut){//first we check which redirect/append it is
- if (!freopen(argv[argc+1], "ab", stdout)){//do the coresponding freopen and check if it's null
- fprintf(stderr, "Error: Failed to append output to: ");//and do the error handling
- perror(argv[argc+1]);
- exit(-1);
- }
- }//repeat for the next two
- else if (redirectOut){
- if (!freopen(argv[argc+1], "wb", stdout)){
- fprintf(stderr, "Error. Failed to redirect output to: ");
- perror(argv[argc+1]);
- exit(-1);
- }
- }
- else if (redirectIn){
- if (!freopen(argv[argc+1], "rb", stdin)){
- fprintf(stderr, "Error. Failed to redirect input from: ");
- perror(argv[argc+1]);
- exit(-1);
- }
- }
- execvp(argv[0], argv);//where all the work is done
- perror(argv[0]);
- exit(1);
- }
- else if (pid > 0){//parent process
- wait(&status);
- }
- else{//should the unimaginable happen
- perror("fork");
- }
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement