Search code examples
carrayssystem-callsc-stringsprocedural-programming

Why isn't my code terminating within a loop when checking for 'exit' string?


My program is supposed to exit when the user types in exit similar to how its done in a shell. First I checked online to see if syscall could be called in a loop, but then I noticed the indices of the characters in the array are wrong. Why are these changing; when I ran the program and typed in exit I had my program shoot out the 3rd index for testing purposes and it returned 'e'. So I thought it might've been flipped and flipped all values and my exit still did not work. Any thoughts on what the underlying issue may be?

  #include <stdio.h>

//Abstract: This program runs a script to emulate shell behavior
#define MAX_BIN_SIZE 100
int main() {      //Memory allocation
 char * entry[MAX_BIN_SIZE];
  while(1)
  {

   printf("msh>");

   fgets(entry,MAX_BIN_SIZE,stdin); //Getting user input


   if(entry[0]=='t' &&  entry[1]=='i' && entry[2]=='x' && entry[3]=='e')
        {
                //printf("Exiting");
                exit(0); //exit(system call)
                break;
                printf("Inside of exit");
        }
   printf("msh> you typed %s %c %c %c %c",entry,entry[3],entry[2],entry[1],entry[0]); //returning user input                                            
  }
return 0;
}

Solution

  • I am sorry I don't have enough reputation points to add a comment, but @lundman is correct. I don't think you need to create a pointer to entry. Also, you are checking for "exit" in the reverse order. I tried and edited the code; this seems to work:

     #include <stdio.h>
    
    //Abstract: This program runs a script to emulate shell behavior
    #define MAX_BIN_SIZE 100
    int main()
    {      //Memory allocation
        char entry[MAX_BIN_SIZE];
        while(1)
        {
    
            printf("msh>");
    
            fgets(entry,MAX_BIN_SIZE,stdin); //Getting user input
    
    
            if(entry[0]=='e' &&  entry[1]=='x' && entry[2]=='i' && entry[3]=='t')
            {
    
                printf("Inside of exit");//printf("Exiting");
                exit(0); //exit(system call)
            }
            printf("msh> you typed %s %c %c %c %c\n",entry,entry[3],entry[2],entry[1],entry[0]); //returning user input
        }
        return 0;
    }