Kundan Kumar
Kundan Kumar

Reputation: 2002

Implementation of shell like feature within C program using unix system calls

Can someone please suggest what is wrong with this program.I am trying to implement shell like feature by creating a child process here. On giving a command having single word like ls or pwd it works but command with multiple words like ls -lrt or who am i is not working. There is something silly mistake that I am doing but unable to debug.

    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    #include <iostream>
    #include <wait.h>
    #include <errno.h>
    #include <sys/types.h>
    #include <cstdlib>
    #define BUFSIZE  200
    #define ARGVSIZE 40
    #define DELIM    "\n\t\r"

    int main ()
    {
      int i,n;
      char buf[BUFSIZE + 1] ;
      char * str = "Shell > ";
      char * clargs[ARGVSIZE] ;
      int returnstatus;
      for(;;)
      {
          n = 1;
          write(STDOUT_FILENO,str,strlen(str));

          read(STDIN_FILENO,buf,BUFSIZE);
          if(!strcmp(buf,"exit\n"))
          {
              perror("exit");
              exit(20);
          }

          clargs[0] = strtok(buf,DELIM);

          while((clargs[n] = strtok(NULL,DELIM)) != NULL)
              n++;

          clargs[n] = NULL;

          switch(fork())
          {
          case 0:
          if((execvp(clargs[0],&clargs[0])) < 0)
              exit(200);

          default:
          wait(&returnstatus);
          printf("Exit status of command : %d\n",WEXITSTATUS(returnstatus));
          for(int i =0; i <= n;i++)
              clargs[i] = "\0";

          for(int i =0; i < BUFSIZE+1;i++)
              buf[i] = '\0';
      }
  }

  return 0;

}

Upvotes: 0

Views: 1363

Answers (1)

ugoren
ugoren

Reputation: 16441

You don't have a space in DELIM.
When trying to run ls -lrt, you want to run the ls executable, with two arguments - ls and -lrt.
But your strtok wouldn't break ls -lrt in two. So you're actually trying to run a program called ls -lrt, and there's no such program.

Adding a space to DELIM should solve it.

Not that it won't be good enough for some cases. E.g. when running echo "a b", you want "a b" to be one parameter, because of the parenthesis. strtok would break it into two. A real shell does more complicated parsing.

Upvotes: 4

Related Questions