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? Here is my code below for the pipe function. I'd greatly appreciate help from someone. Thanks!
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 ( (pid = fork()) == -1 ){
fprintf(stderr,"Fork error. Exiting.\n"); /* something went wrong with forking */
}
if (pid ==0) {
// first child process
if(pipe(commpipe)){ /* Setup communication pipeline */
fprintf(stderr,"Pipe error\n");
exit(1);
}
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);
I created the pipe in the parent process, however, the pipe still doesn't work. Are you able to let me know what I'm still doing wrong? I've pasted the new code below. Thanks!
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 ( (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);