I have written following code to do: ls -l | wc -w, it works:
but when there are not only a single "|", if there are more such as:
ls -l | sort -r | sort | sort -r, This program does not work, i want to know how could i deal with it when there are more "|", another situation is that, if it mixes "|" and "<" or ">", such as: cat < apa | wc | wc >h***, this is also complex, how could i deal with these? thank you very much
(The following is just for a single "|")
void pipeProcess(char *args1[], char *args2[]) {
int thepipe[2], pid;
if(pipe(thepipe) == -1)
oops("Can not get a pipe", 1);
/* Create a new process */
if((pid = fork()) == -1)
oops("Can not fork", 2);
if(pid >0) {/* This is parent process /
close(thepipe[1]); / parent does not write to pipe /
if(dup2(thepipe[0], 0) == -1) / let parent read interface attaches to stdin /
oops("Could not redirect stdin", 3);
close(thepipe[0]); / close thepipe[0] interface because it has attached to stdin */
execvp(args2[0], args2);
oops(*args2, 4);
}
/* Child process executes av[1] and writesinto pipe /
close(thepipe[0]); / Child does not read from pipe */
if(dup2(thepipe[1], 1) == -1)
oops("Could not redirect stdout", 4);
close(thepipe[1]);
execvp(args1[0], args1);
oops(*args1, 5);
}