【发布时间】:2011-04-25 05:25:37
【问题描述】:
基本上我已经使用标准 POSIX 命令创建了一个 shell,我也希望能够实现管道。现在它可以正确处理命令,并且可以使用 & 进行后台处理。但我需要能够使用 | 进行管道传输和 >> 也是如此。 例如这样的: 猫文件1 文件2 >> 文件3 猫文件1 文件2 |更多的 更多文件1 | grep 的东西
这是我目前拥有的代码。我也想避免“系统”调用。我知道你需要使用 dup2,但是我编写代码的方式有点奇怪,所以我希望有人能告诉我在这段代码中实现管道是否可行?谢谢!我知道使用了 dup2,但我也知道。对如何实现 >> as WELL as |
感到困惑#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
void Execute(char* command[],bool BG)
{
//Int Status is Used Purely for the waitpid, fork() is set up like normal.
int status;
pid_t pid = fork();
switch(pid)
{
case 0:
execvp(command[0], command);
if(execvp(command[0], command) == -1)
{
cout << "Command Not Found" << endl;
exit(0);
}
default:
if(BG == 0)
{
waitpid(pid, &status, 0);
//Debug cout << "DEBUG:Child Finished" << endl;
}
}
}
bool ParseArg(char* prompt, char* command[], char Readin[],bool BG)
{
fprintf(stderr, "myshell>");
cin.getline(Readin,50);
prompt = strtok(Readin, " ");
int i = 0;
while(prompt != NULL)
{
command[i] = prompt;
if(strcmp(command[i], "&") == 0){
//Debug cout << "& found";
command[i] = NULL;
return true;
}
//Debug cout << command[i] << " ";
i++;
prompt = strtok(NULL, " ");
}
return false;
}
void Clean(char* command[])
{
//Clean Array
for(int a=0; a < 50; a++)
{
command[a] = NULL;
}
}
int main()
{
char* prompt;
char* command[50];
char Readin[50];
bool BG = false;
while(command[0] != NULL)
{
Clean(command);
BG = ParseArg(prompt, command, Readin, BG);
if(strcmp(command[0], "exit") == 0 || strcmp(command[0], "quit") == 0 )
{
break;
}
else
{
Execute(command,BG);
}
}
return 1;
}
【问题讨论】:
-
你为什么要避免系统调用?可移植性?您可以尽可能地坚持使用 POSIX 指定的系统调用。此外,您的 shell 是 C 和 C++ 的奇怪组合。