Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Here is the link to the c file and the slides for lab 9 (in case you want those)

ID: 3815905 • Letter: H

Question

Here is the link to the c file and the slides for lab 9 (in case you want those):

https://www.dropbox.com/sh/oowh7tytlo6t4p8/AAATK2OOYU7ncreCZEY6reRsa?dl=0

PURPOSE: The purpose of this lab is to allow students to learn a user interface aspect of a UNIX shell. Student will work with process management and some basic system calls. Important note: please use spl, sp2, sp3, or atoz servers for this lab. UNIX Shell We will start with 3 built-in commands: cd (change directory), pwd (print working directory), and exit (exit shell) The built-in functions are not executed by forking and executing an executable. Instead, the shell process executes them itself. Your shell is basically an interactive loop: it repeatedly prints a prompt "csc60msh parses the input, executes the command specified on that line of input, and waits for the command to finish.

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_CMD_LEN 128

int cd(char *pth)
{
   char path[MAX_CMD_LEN];
   strcpy(path,pth);
   char cwd[MAX_CMD_LEN];
   getcwd(cwd,sizeof(cwd));
   strcat(cwd,"/");
   strcat(cwd,path);
   int ret = chdir(path);
   if(ret!=0)
   printf("Error: Could not change to the directory ");
   else
   system("pwd"); // printing new changed directory
   return 0;
}

int hasPrefix(char const *p, char const *q)
{
   int i = 0;
   for(i = 0;q[i];i++)
   {
       if(p[i] != q[i])
       return -1;
   }
   return 0;
}

int main()
{
char cmd[MAX_CMD_LEN];

char buf[1000];
int i, current = 0;

char *tok;
tok = strtok (cmd," ");

while (1)
{
       bzero(cmd, MAX_CMD_LEN);
       printf("csc60msh > ");
       fgets(cmd, MAX_CMD_LEN, stdin);

       if (cmd[strlen(cmd) - 1] == ' ')
       {
       cmd[strlen(cmd) - 1] = '';
       }

   if(hasPrefix(cmd,"cd") == 0)
       {
       tok = strchr(cmd,' ');
       if(tok)
       {
           char *tempTok = tok + 1;
           tok = tempTok;
           char *locationOfNewLine = strchr(tok, ' ');
           if(locationOfNewLine)
           {
               *locationOfNewLine = '';
           }
           printf("cd location is : %s ", tok);
           cd(tok);
           }
          
           else // if user do not enter anything after
           {
               cd(getenv("HOME"));
           }
       }
      
       if(hasPrefix(cmd,"pwd") == 0)
       {
           system("pwd");
       }
       if (strcmp(cmd, "exit") == 0)
           exit(0);
   }
return 0;
}