Grundsätzlich habe ich eine Shell mit POSIX-Standardbefehlen erstellt, ich möchte auch Piping implementieren können. Im Moment behandelt es Befehle korrekt und kann Hintergrundverarbeitung mit & durchführen. Aber ich muss mit | pipen können und >> auch. Zum Beispiel so etwas wie: cat file1 file2 >> file3 cat file1 file2 | mehr mehr file1 | grep stuffImplementieren von Pipes in einer C-Shell (Unix)
Hier ist der Code, den ich derzeit habe. Ich möchte auch "SYSTEM" -Aufrufe vermeiden. Ich weiß, dass Du dup2 verwenden musst, aber die Art und Weise, wie ich meinen Code gemacht habe, ist etwas merkwürdig, also hoffe ich, dass mir jemand sagen kann, ob es möglich ist, Pipes in diesem Code zu implementieren? Vielen Dank! Ich weiß, dup2 wird verwendet, aber auch im def. verwirrt darüber, wie man >> ebenso wie |
#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;
}
Warum haben Sie versucht, Systemaufrufe zu vermeiden? Portabilität? Sie können so lange wie möglich bei den von POSIX angegebenen Systemaufrufen bleiben. Außerdem ist Ihre Shell eine seltsame Mischung aus C und C++. – nategoose