title: Executing shell commands with execvp()
body: <p>I want to write a program which acts like a Linux shell. I started with writing a small program to execute the "ls" command. What I can't figure out is how should I proceed in order to make my program respond to any command like the shell does. ( e.g cat, cd, dir).</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;stdlib.h&gt;
  #define MAX 32
  using namespace std;
  
  int main() {
      pid_t c; 
      char s[MAX];
      int fd[2];
      int n;
  
      pipe(fd);
      c = fork();
  
      if(c == 0) {
          close(fd[0]);
          dup2(fd[1], 1);
          execlp("ls", "ls", "-l", NULL);
          return 0;
      } else {
          close(fd[1]);
          while( (n = read(fd[0], s, MAX-1)) &gt; 0 ) {
              s[n] = '\0';
              cout&lt;&lt;s;
          }
          close(fd[0]);
          return 0;
      }
  
      return 0;
  }
  </code></pre>
  
  <p>How can I make my program read what the user types in and passes it to <code>execlp</code> (or something similar that does the same thing)?</p>