added pipe support
This commit is contained in:
@@ -5,6 +5,41 @@
|
|||||||
#include<string.h>
|
#include<string.h>
|
||||||
#include<readline/readline.h>
|
#include<readline/readline.h>
|
||||||
#include<readline/history.h>
|
#include<readline/history.h>
|
||||||
|
int seperatePipe(char **args) {
|
||||||
|
for(int i = 0; args[i] != NULL; i++) {
|
||||||
|
if (strcmp(args[i], "|") == 0) return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
void executePipe(char **args, int pipeIndex) {
|
||||||
|
args[pipeIndex] = NULL;
|
||||||
|
char **cmd1 = args;
|
||||||
|
char **cmd2 = args + pipeIndex + 1;
|
||||||
|
int fd[2];
|
||||||
|
pipe(fd);
|
||||||
|
pid_t pid1 = fork();
|
||||||
|
if (pid1 == 0) {
|
||||||
|
dup2(fd[1], STDOUT_FILENO);
|
||||||
|
close(fd[0]);
|
||||||
|
close(fd[1]);
|
||||||
|
execvp(cmd1[0], cmd1);
|
||||||
|
perror("tinysh");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
pid_t pid2 = fork();
|
||||||
|
if (pid2 == 0) {
|
||||||
|
dup2(fd[0], STDIN_FILENO);
|
||||||
|
close(fd[0]);
|
||||||
|
close(fd[1]);
|
||||||
|
execvp(cmd2[0], cmd2);
|
||||||
|
perror("tinysh");
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
close(fd[0]);
|
||||||
|
close(fd[1]);
|
||||||
|
if (pid1 > 0) wait(NULL);
|
||||||
|
if(pid2 > 0) wait(NULL);
|
||||||
|
}
|
||||||
int handleBuiltins(char **args) {
|
int handleBuiltins(char **args) {
|
||||||
if(strcmp(args[0], "cd") == 0) {
|
if(strcmp(args[0], "cd") == 0) {
|
||||||
chdir(args[1] == NULL ? getenv("HOME") : args[1]);
|
chdir(args[1] == NULL ? getenv("HOME") : args[1]);
|
||||||
@@ -41,6 +76,13 @@ int main() {
|
|||||||
char **parsed = parse(line);
|
char **parsed = parse(line);
|
||||||
if(parsed[0] == NULL) { free(parsed); free(line); continue; }
|
if(parsed[0] == NULL) { free(parsed); free(line); continue; }
|
||||||
if(handleBuiltins(parsed)) { free(line); free(parsed); continue; }
|
if(handleBuiltins(parsed)) { free(line); free(parsed); continue; }
|
||||||
|
int pipeIndex = seperatePipe(parsed);
|
||||||
|
if (pipeIndex != -1) {
|
||||||
|
executePipe(parsed, pipeIndex);
|
||||||
|
free(line);
|
||||||
|
free(parsed);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
pid_t pid = fork();
|
pid_t pid = fork();
|
||||||
if(pid == 0) {
|
if(pid == 0) {
|
||||||
if(execvp(parsed[0], parsed) == -1 ) {
|
if(execvp(parsed[0], parsed) == -1 ) {
|
||||||
|
|||||||
Reference in New Issue
Block a user