Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

Mini Project 1

Shell interpreter using C programming

Name: Varsha Singh Login ID: varssin@amazon.com


Code:

#include<stdio.h> // printf
#include<string.h> // to compare strings
#include<stdlib.h> // exit()
#include<unistd.h> //
#include<sys/types.h>
#include<sys/wait.h> // sleep
#include<fcntl.h> // open , write
#include<errno.h> // for showing error
#include<readline/readline.h> // prompt
#include<readline/history.h> // save the command history

// Clearing the shell using escape sequences


#define clear() printf("\033[H\033[J")
/* \033[H moves the cursor to the top left corner of the screen (ie, the first column of the first row in the screen).
and
\033[J clears the part of the screen from the cursor to the end of the screen.
*/

// Welcomig
void init_shell()
{
    clear();
    char* username = getenv("USER");
    printf("\n\n\n\n******************************************");
    printf("\n\n\n\t\t**** Welcome %s ****",username);
    printf("\n\n\t\t-BY VARSHA SINGH-");
    sleep(2);
    clear();
}
void mycp(char *from,char *to)
{
    int fd1=open(from,O_RDONLY);
    if(fd1==-1)
  {
        perror("Error: ");
        return;
  }
    int fd2=open(to,O_CREAT|O_WRONLY,0777);
    static char buf[1];
    while(read(fd1,buf,1))
  {
        write(fd2,buf,1);
  }
}
  
void myrm(char *file) // deletes only single file at a time
{
    if (remove(file) == 0) {
        printf("The file is deleted successfully.");
  }
    else
        perror("Error: ");
  
}
void mymv(char *file,char *newName)
{
    int value;
 
    // File name is changed here
    value = rename(file, newName);
 
    // Print the result
    if(!value)
        printf("%s", "File name changed successfully");
    else
        perror("Error");  
}
// Function to take input
int takeInput(char* str)
{
    char* buf;

    buf = readline(" $ ");


    if (strlen(buf) != 0) {
        add_history(buf);
        strcpy(str, buf);
        return 0;
  }
    else {
        return 1;
  }
}

// Function to print Current Directory.


void printDir()
{
    char cwd[1024];
    getcwd(cwd, 1024);
    printf("\nDir: %s", cwd);
}
void myhead(int n, char *s)
{
    int fd=open(s,O_RDONLY);
    if(fd==-1)
        printf("no such file or dir exist");
    else
  {
        static char buf[1];
        int ct=1;
        while( read(fd,buf,1) && ct<=n )
    {
            if(buf[0]=='\n')
                ct++;
            printf("%s",buf);
    } 
  }
}

void mytail(int n, char *s)


{
        int fd=open(s,O_RDONLY);
        if(fd==-1)
                printf("no such file or dir exist");
        else
    {
            static char buf[1];
            int ct=0;
            while(read(fd,buf,1))
      {
                if(buf[0]=='\n')
                       ct++;
      }
            ct=ct-n;
            n=1;
            fd=open(s,O_RDONLY);
            while(n<ct && read(fd,buf,1))
      {
                if(buf[0]=='\n')
                    n++;
      }
            if(ct>0)lseek(fd,1,SEEK_CUR);
            while(read(fd,buf,1))
      {
                printf("%s",buf);
      }
    }
}

void mycat(char *s)


{
    int fd=open(s,O_RDONLY);
    if(fd==-1)
        printf("no such file or dir exist");
    else
  {
        static char buf[1];
        int ct=1;
        while( read(fd,buf,1))
    {
            printf("%s",buf);
    } 
  }
}
// Function where the system command is executed
void execArgs(char** parsed)
{
    // Forking a child
    pid_t pid = fork();

    if (pid == -1) {
        printf("\nFailed forking child..");
        return;
  }
    else if (pid == 0)// child process
  {
        if (execvp(parsed[0], parsed) < 0) {
            printf("\nCould not execute command..");
    }
        exit(0);
  }
    else {
        wait(NULL); // waiting for child to terminate
        return;
  }
}

// Help command builtin


void openHelp()
{
    puts("\n***WELCOME TO MY SHELL HELP***"

        "\nList of Commands supported:"


        "\n>mycd"
        "\n>exit"
        "\n>myhead"
        "\n>mytail"
        "\n>mycat"
        "\n>myrm"
        "\n>mycp"
        "\n>mycat"
        "\n>all other default commands supported by linux"
        "\n>extra space handled");
    return;
}

// Function to execute builtin commands


int ownCmdHandler(char** parsed)
{
    int NoOfOwnCmds = 10, i, switchOwnArg = 0;
    char* ListOfOwnCmds[NoOfOwnCmds];
    char* username;

    ListOfOwnCmds[0] = "exit";
    ListOfOwnCmds[1] = "mycd";
    ListOfOwnCmds[2] = "help";
    ListOfOwnCmds[3] = "hello";
    ListOfOwnCmds[4] = "myhead";
    ListOfOwnCmds[5] = "mytail";
    ListOfOwnCmds[6] = "mycat";
    ListOfOwnCmds[7] = "mymv";
    ListOfOwnCmds[8] = "myrm";
    ListOfOwnCmds[9] = "mycp";
    for (i = 0; i < NoOfOwnCmds; i++) {
        if (strcmp(parsed[0], ListOfOwnCmds[i]) == 0) {
            switchOwnArg = i + 1;
            break;
    }
  }

    switch (switchOwnArg) {
    case 1:
        printf("\nNamaste\n");
        exit(0);
    case 2:
        chdir(parsed[1]);
        return 1;
    case 3:
        openHelp();
        return 1;
    case 4:
        username = getenv("USER");
        printf("\nHello %s.\nMind that this is "
            "not a place to play around."
            "\nUse help to know more..\n",
            username);
        return 1;
    case 5: //head -n 5 file
        if(strcmp(parsed[1],"-n")==0)
            myhead(atoi(parsed[2]),parsed[3]);
        else
            myhead(10, parsed[1]);
        return 1;
    case 6:
        if(strcmp(parsed[1],"-n")==0)
            mytail(atoi(parsed[2]),parsed[3]);
        else
            mytail(10, parsed[1]);
      
        return 1;
    case 7:
            mycat(parsed[1]);
        return 1;
    case 8:
        mymv(parsed[1],parsed[2]);
        return 1;
    case 9:
        myrm(parsed[1]);
        return 1;
    case 10:
        mycp(parsed[1],parsed[2]);
        return 1;
    default:
        break;
  }

    return 0;
}

// function for parsing command words


void parseSpace(char* str, char** parsed)
{
    int i;

    for (i = 0; i < MAXLIST; i++) {


        parsed[i] = strsep(&str, " ");

        if (parsed[i] == NULL)
            break;
        if (strlen(parsed[i]) == 0)
            i--;
  }
}

int processString(char* str, char** parsed )


{
    parseSpace(str, parsed);
    if (ownCmdHandler(parsed))
        return 0;
    return 1;
}

int main()
{
    char inputString[1000], *parsedArgs[100];

    int execFlag = 0;
    init_shell();

    while (1) {
        // print shell line
        printDir();
        // take input
        if (takeInput(inputString))
            continue;
        // process
        execFlag = processString(inputString,
        parsedArgs);
        // execflag returns zero if there is no command
        // or it is a builtin command,
        // 1 if it is a simple command

        // execute
        if (execFlag == 1)
            execArgs(parsedArgs);

  }
    return 0;
}

You might also like