【发布时间】:2015-02-13 23:58:40
【问题描述】:
我想编写一个类似于 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(或类似的东西)?
【问题讨论】:
-
"... 让我的程序响应任何命令..." 在父进程中,您有
fd[1]文件描述符,您可以使用它来编写关于已建立的pipe()的东西。请注意,您列出的命令不需要任何输入交互。