hefouied
hefouied

Reputation: 1

Creating a basic shell in C. Segmentation fault error message

I am attempting to create a a basic linux shell in c. I am getting a Segmentation fault core dumped error message for some reason.

I attempted to run the ls command and got the error message. Help would be appreciated.

void  execute(char **argv)
{
     pid_t  pid;
     int status;
     pid = fork();

     if (pid  < 0) {     /* fork a child process           */
          printf("*** ERROR: forking child process failed\n");
          exit(1);
     }
     else if (pid == 0) {          /* for the child process:         */
          if (execvp(*argv, argv) < 0) {     /* execute the command  */
               printf("*** ERROR: exec failed\n");
               exit(1);
          }
     }
     else {                                  /* for the parent:      */
          while (wait(&status) != pid)       /* wait for completion  */
               ;
     }
}

void  main(void)
{
     char line[1024];             /* the input line                 */
     char *argv[64];              /* the command line argument      */
     char *tokens[64];
     int numtokens;

     while (1) {                   /* repeat until done ....         */
          printf("Shell -> ");     /*   display a prompt             */
          fgets(line, 64, stdin);              /*   read in the command line     */
          printf("\n");
         // parse(line, argv);
          if ((tokens[0] = strtok(line, " \n\t")) == NULL) continue;
          numtokens = 1;
          while((tokens[numtokens] = strtok(NULL, " \n\t")) != NULL) numtokens++;

          if (strcmp(argv[0], "exit") == 0)  /* is it an "exit"?     */
               exit(0);            /*   exit if it is                */
          execute(argv);           /* otherwise, execute the command */
     }
}

Upvotes: 0

Views: 140

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

You are using elements of argv without initializing them in your main function.

You may want to use tokens instead.

Upvotes: 2

Related Questions