Home > Software engineering >  Is alternating pipes possible in C?
Is alternating pipes possible in C?

Time:06-01

I'd like to know if alternating pipes is possible in C.
The following is the code I thought about, minus error checking and the program setter. As you can see I only use two pipes in alternating order, which is basically the question I'm asking: Would this be possible or do I have to create a new pipe when the pipes before have been used? (In this example you could remove the fourth fork and let it end in the third fork which would work flawless from my experience).

int main(int argc, char *argv[]) {

int pip[2], pop[2];
pid_t pid1, pid2, pid3, pid4;

pipe(pip);
pipe(pop);

//Program execute

pid1 = fork();
if(pid1 == 0) {
    dup2(pip[WRITE], STDOUT_FILENO);
    //close all ends here
    execvp(prog1A[0], prog1A);
}

pid2 = fork();
if(pid2 == 0) {
    dup2(pip[READ], STDIN_FILENO);
    dup2(pop[WRITE], STDOUT_FILENO);
    //close all ends here
    execvp(prog2A[0], prog2A);
}

pid3 = fork();
if(pid3 == 0) {
    dup2(pop[READ], STDIN_FILENO);
    dup2(pip[WRITE], STDOUT_FILENO);
    //close all ends here
    execvp(prog3A[0], prog3A);
}

pid4 = fork();
if(pid4 == 0) {
    dup2(pip[READ], STDIN_FILENO);
    //close all ends here
    execvp(prog4A[0], prog4A);
}

//close all ends here
//wait for all pids here
}

Would this be possible in C?

CodePudding user response:

You need separate pipes. The way you wrote it, both pid2 and pid4 would have the same pipe connected to their STDIN and steal the incoming byted from each other. Similar of the writing end, several processes writing into the same pipe will get their outputs coming out (mixed) on the reading end.

  • Related