我想写一个像Linux shell一样的程序。我从编写一个小程序开始执行“ ls”命令。我不知道该怎么做才能使我的程序像shell一样响应任何命令。(例如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;
}
如何使我的程序读取用户键入的内容并将其传递给execlp
(或类似的操作相同的东西)?
Shell基本上执行以下操作:
首先构造一个非常简单的外壳。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句