Reputation: 63
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
Reputation: 1091
If I correctly understand a problem, You can:
scanf()
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
Reputation: 36431
A shell basically does the following :
Construct first a very simple shell.
Upvotes: 3