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

Create a simple shell that perform the following: that accepts two command: run

ID: 3674135 • Letter: C

Question

Create a simple shell that perform the following: that accepts two command: run and exit. 1. The run command will execute other programs specified by the users. For example: run Is will execute Is. run Is -I will execute Is -I run date will execute date If user provides an unknown program, the shell should print out an error message, run azzxcd will try to execute azzxcd but will fail. b.The exit command will just exit c.lf user enters an empty command, do nothing and return to the prompt. d. If user enters commands other than run or exit, the shell should print out an error message:

Explanation / Answer

I have written a c shell to do the similar task. I have also coded the exit command to come out of the shell once the exit is run on the terminal.

Working code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

void parseCmd(char* cmd, char** params);
int executeCmd(char** params);

#define MAX_COMMAND_LENGTH 80
#define MAX_NUMBER_OF_PARAMS 10

int main()
{
char cmd[MAX_COMMAND_LENGTH + 1];
char* params[MAX_NUMBER_OF_PARAMS + 1];

int cmdCount = 0;

while(1) {
char* username = getenv("USER");
printf("%s@shell %d> ", username, ++cmdCount);

if(fgets(cmd, sizeof(cmd), stdin) == NULL) break;
if(cmd[strlen(cmd)-1] == ' ') {
cmd[strlen(cmd)-1] = '';
}
parseCmd(cmd, params);
if(strcmp(params[0], "exit") == 0) break;
if(executeCmd(params) == 0) break;
}

return 0;
}

void parseCmd(char* cmd, char** params)
{   
for(int i = 0; i < MAX_NUMBER_OF_PARAMS; i++) {
params[i] = strsep(&cmd, " ");
if(params[i] == NULL) break;
}
}

int executeCmd(char** params)
{
pid_t pid = fork();

if (pid == -1) {
char* error = strerror(errno);
printf("fork: %s ", error);
return 1;
}

else if (pid == 0) {
execvp(params[0], params);

char* error = strerror(errno);
printf("shell: %s: %s ", params[0], error);
return 0;
}
else {
int childStatus;
waitpid(pid, &childStatus, 0);
return 1;
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote