nightfury94
nightfury94

Reputation: 63

Executing shell commands with execvp()

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).

#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 make my program read what the user types in and passes it to execlp (or something similar that does the same thing)?

Upvotes: 4

Views: 1444

Answers (2)

kestasx
kestasx

Reputation: 1091

If I correctly understand a problem, You can:

  • read array of strings with scanf()
  • run it as a command with execvp() (it works the same as execlp(), but You can pass all arguments as an array).

Something like:

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

Upvotes: 1

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36431

A shell basically does the following :

  1. reads a line from stdin
  2. parses that line to make a list of words
  3. forks
  4. then the shell (parent process) waits until the end of the child, while the child execs to execute the code of the command represented by the list of words extracted from the input line.
  5. the shell then restarts at step 1.

Construct first a very simple shell.

Upvotes: 3

Related Questions