我希望编写一个像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()
上写入某些内容。请注意,您列出的命令不需要任何输入交互。 - πάντα ῥεῖ