EDIT 4: If I only close pp[0][0] on the father, it works. I'm confused.
EDIT 3: I made this code that you can try to compile and run.
As you can see, I made 2 pipes with pipe and 2 childrens with fork.
Then I close the pipes that I'm not going to use in the childrens and in the father.
But when I run the code I keep getting -1 when a child try to write in pp[1][1].
I want that the father write "Hello World" in pp[0][1], then the first child read from pp[0][0] and write it in pp[1][1] (Here I get -1 when I try to write). Then the second children should read from pp[1][0] and write the content in the stdout.
Hope you can help me.
#define MYNAME "testing"
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int n_childrens;
int* pp[2];
int actual_p;
int main(int argc, char* argv[]) {
n_childrens = 2;
int i, j, aux, test;
char buff_test[20] = "Hello World n";
char buff_test2[20];
printf("Making %d pipesn",n_childrens);
for (i = 0; i < n_childrens; i++) {
pp[i] = (int*) malloc(sizeof (int)*2);
if (pipe(pp[i]) < 0) {
perror(MYNAME": Error in pipe()");
exit(1);
}
}//for
for (i = 0; i < n_childrens; i++) {
printf("I am the father with pid: %d and i'm going to make a childrenn", getpid());
switch (fork()) {
case -1:
perror(MYNAME": Fork failedn");
exit(1);
case 0:
actual_p = i;
printf("I'm the children with pid: %d and I'm going to close all the pipes I will not usen", getpid());
for (aux = 0; aux < n_childrens; aux++) { /*Con este for cerramos los pipes innecesarios en el hijo*/
if (aux == actual_p) {
printf("I'm the children %d and I close the pipe[%d][1]n", getpid(), aux);
close(pp[aux][1]);
} else if (aux == actual_p + 1) {
printf("Im the children %d and im closing the pipe[%d][0] n", getpid(),aux);
close(pp[aux][0]);
}
else {
printf("I'm the children %d and I close the pipe[%d]n", getpid(), aux);
close(pp[aux][0]);
close(pp[aux][1]);
}
}
if (actual_p == 0) {
printf("I'm the children with pid: %d and I'm going to read the pipe and write in the other n", getpid());
read(pp[0][0],buff_test2,sizeof(buff_test2));
test = write(pp[1][1], buff_test2, sizeof (buff_test));
}
else{
printf("I'm the second children and want to write in stdoutn");
read(pp[1][0],buff_test2,sizeof(buff_test2));
write(1,buff_test2,sizeof(buff_test2));
printf("Character wroten: %dn", test);
}
close(pp[actual_p][0]);
close(pp[actual_p][1]);
exit(0);
default:
if(i==0){
printf("We close the unnecesary pipes on the father (?) n");
close(pp[0][0]);
for (j = 1; j < n_childrens; j++) {
close(pp[j][0]);
close(pp[j][1]);
}
}
}
}
printf("I'm the father and I'm going to write in the pipen");
write(pp[0][1],buff_test,sizeof(buff_test));
for(i=0;i<2;i++)
wait(NULL);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire