基本上,我使用标准的POSIX命令创建了一个shell,我希望能够实现管道功能。目前,它可以正确处理命令,并且可以通过&符号进行后台处理。但是我还需要能够使用|和>>进行管道操作。
例如:
cat file1 file2 >> file3
cat file1 file2 | more
more file1 | grep stuff
以下是我当前的代码。我也想避免使用“SYSTEM”调用。我知道需要使用dup2,但是我的代码方式有些奇怪,所以我希望有人能告诉我是否可行在这个代码中实现管道?谢谢!我知道dup2被使用了,但是对于如何实现>>和|也感到困惑。
以下是我当前的代码。我也想避免使用“SYSTEM”调用。我知道需要使用dup2,但是我的代码方式有些奇怪,所以我希望有人能告诉我是否可行在这个代码中实现管道?谢谢!我知道dup2被使用了,但是对于如何实现>>和|也感到困惑。
#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;
}