Hello,
I am trying to create a pipe that will direct stdout to in side of the pipe, and stdin to the out side of the pipe - I created two child processes to handle this. However, my pipe doesn't seem to be working correctly. Did I use execv() correctly? Command1[] and command2[] represent the two commands in the pipe statement that is written in a cissh shell (e.g. "ls -C | sort -r). So I want cisshPipe.c to direct stdout to the in side of the pipe and direct stdin to the out side of the pipe so that the command "ls -C | sort -r" would print a sorted list in reverse order of the files in the cissh directory. Below is my code for the pipe function. I'd greatly appreciate help from someone.Thanks!
/* cisshPipe.c
*/
/* External functions --
*/
extern void error(char* message);
//extern wait(int*status);
/* cisshPipe(char* command1[], char* command2[])
* handles command lines with pipes.
*/
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
void
cisshPipe(char* command1[], char* command2[])
{
pid_t pid;
pid_t pid1;
int status;
int commpipe[2]; /* This holds the input and output of the pipe */
if(pipe(commpipe)){ /* Setup communication pipeline */
fprintf(stderr,"Pipe error\n");
exit(1);
}
if ( (pid = fork()) == -1 ){
fprintf(stderr,"Fork error. Exiting.\n"); /* something went wrong with forking */
}
if (pid ==0) {
// first child process
close(commpipe[1]);
dup2(commpipe[0],1); /* Replace in side of pipe with stdout */
close(commpipe[0]);
execv(command1[0], command1);
if ( (pid1 = fork()) == -1 ){
fprintf(stderr,"Fork error. Exiting.\n"); /* something went wrong with forking */
}
if(pid1 == 0){
/* second child process */
close(commpipe[0]);
dup2(commpipe[1],0); /* Replace out side of pipe with stdin */
close(commpipe[1]);
execv(command2[0], command2);
}
else {
close(commpipe[1]);
close(commpipe[0]);
if(wait(&status) < 0)
{
error("cissh: error waiting for child.");
perror("wait");
}
}
}
else {
close(commpipe[1]);
close(commpipe[0]);
if(wait(&status) < 0)
{
error("cissh: error waiting for child.");
perror("wait");
}
}
}