Create simple shell in C with a "Set prompt" command

2.2k Views Asked by At
#include <string.h>
#include <errno.h>

#define MAX_LENGTH 1024
#define SPACES " \t\r\n"

int main(int argc, char *argv[]){
char line[MAX_LENGTH];
char *cmd;
char *PROMPT = "SUPER SHELL!!";

while(1){
    printf(PROMPT);
    if (!fgets(line, MAX_LENGTH, stdin)) break;

    //parse and execute commands

    if((cmd = strtok(line, SPACES))){
    // clean errors
    errno=0;
    if (strcmp(cmd, "quit") ==0){
    break;
    }
    else if(strcmp(line, "Set Prompt") == 0){
    char *arg = strtok(0, SPACES);
    if (!arg){
        fprintf(stderr, "You were missing a prompt. \n");
    }
    else {PROMPT =arg;
  }
    }
  else system(line);
  if(errno) perror ("Command failed. sorry");
  }
  return 0;
  }

I am writing a program in which I have to write my own shell in C. There must be two commands : quit, which quits the program, and Set Prompt which changes the prompt. For some reason quit works but Set prompt does not. How can I fix this? Thank you

1

There are 1 best solutions below

0
On

Your program indeed seems to have a lot of problems.

Trying to give you some hints, where to improve without solving the whole exercise for you, here some points I stumbled across:

Gemeral problems

The program doesn't compile!

  1. missing closing brace (most probably on line 35) resulting in:

    error: expected declaration or statement at end of input

  2. missing include of stdio.h resulting in:

    error: ‘stdin’ undeclared (first use in this function) ...

  3. the last one rather a result of the -Werror switch used in my compilation attempt:

    error: format not a string literal and no format arguments [-Werror=format-security]

    Nevertheless it might not be the worst idea to change printf(PROMPT); on line 13. (see: http://en.wikipedia.org/wiki/Uncontrolled_format_string)

Logic problems

  1. the block following

    else if(strcmp(line, "Set Prompt") == 0){ on line 24

    will never be executed as the prior call to strtok() will have replaced any input of the form "Set Prompt whatever..." with "Set\0Prompt whatever..." not(!) with "Set Prompt\0whatever..."

  2. Even after fixing this issue there will still be some spooky behavior left.

    To reproduce try changing the set prompt command to "SetPrompt" in your code and start a session. I'd be surprised if you came up with a different result than me:

    SUPER SHELL!!SetPrompt myprompt:
    myprompt:what the hell is going on here?
    sh: 1: what: not found
    ell is going on here?
    quit
    

    Hint: the simple assignment on line 29 else {PROMPT =arg; will not do, as the memory arg is pointing to will be overwritten the next time fgets(line, MAX_LENGTH, stdin) gets called on line 14.

    Try to reserve some extra memory for the prompt string and look up strcpy()