Running shell commands with execvp ()

I want to write a program that acts like a Linux shell. I started writing a small program to execute the ls command. I can’t understand how I should act in order for my program to respond to any command, as the shell does. (e.g. cat, cd, dir).

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#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)) > 0 ) {
            s[n] = '\0';
            cout<<s;
        }
        close(fd[0]);
        return 0;
    }

    return 0;
}

How can I get my program to read what the user enters and passes it into execlp(or something like that that does the same)?

+4
source share
2 answers

The shell basically does the following:

  • reads a string from stdin
  • parses this line to make a list of words
  • Forks
  • ( ) , execs , , .
  • 1.

.

+3

, :

  • scanf()
  • execvp() ( , execlp(), ).

- :

char args[100][50];
int nargs = 0;
while( scanf( " %s ", args[nargs] ) )
   nargs++;
args[nargs] = NULL;
/* fork here *
...
/* child process */
execvp( args[0], args );
+1

All Articles