Created
April 24, 2023 14:16
-
-
Save Ts-Pytham/d1df5b22374ad2e5223b1133b6a2c168 to your computer and use it in GitHub Desktop.
Envio de información por varias tuberias
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <string.h> | |
#include <wait.h> | |
#include <time.h> | |
#define BUFFER 1024 | |
/* | |
Hijo n | |
Padre -> Hijo 1 -> Hijo 2 --- | |
^ | | |
| | | |
|------------------------| | |
*/ | |
int main(){ | |
int n, i; | |
char message[BUFFER]; | |
printf("Ingrese la cantidad de hijos a crear: \n"); | |
scanf("%d", &n); | |
getchar(); // consume el carácter de nueva línea | |
int n_tuberias = n + 1; | |
int** fd = malloc(n_tuberias * sizeof(int*)); | |
for(int j = 0; j != n_tuberias; ++j){ | |
fd[j] = malloc(2 * sizeof(int)); | |
pipe(fd[j]); | |
} | |
for(i = 0; i < n; ++i){ | |
if(fork() == 0){ | |
for(int j = 0; j < n_tuberias; ++j){ | |
if (i == j){ //Estamos en la tuberia donde el hijo recibe info: ej: Padre -> hijo | |
close(fd[j][1]); //Cerramos escritura | |
} | |
else if(i+1 == j){ //Estamos en la tuberia donde el hijo envia info: ej: Hijo -> Hijo2 | |
close(fd[j][0]); //Cerramos lectura | |
} | |
else{ // Estamos en otra tuberia que no le interesa al hijo | |
close(fd[j][1]); //Cerramos escritura | |
close(fd[j][0]); //Cerramos lectura | |
} | |
} | |
break; | |
} | |
} | |
if(n == i){ // Padre | |
for(int j = 0; j != n_tuberias; ++j){ | |
if(j == 0){ //Primera tubería, cerramos lectura | |
close(fd[0][0]); //Cerramos lectura | |
} | |
else if(j == n_tuberias - 1){ //Estamos en la última, cerramos solo escritura, necesitamos leer | |
close(fd[j][1]); //Cerramos escritura | |
} | |
else{ // Tuberias innecesarias | |
close(fd[j][1]); //Cerramos escritura | |
close(fd[j][0]); //Cerramos lectura | |
} | |
} | |
printf("[Padre (%d)]: Ingrese una letra sin espacios\n", getpid()); | |
fgets(message, BUFFER, stdin); | |
write(fd[0][1], &message, BUFFER); | |
usleep(100); | |
read(fd[n_tuberias - 1][0], &message, BUFFER); | |
printf("[Padre (%d)]: Recibí un mensaje: %s\n", getpid(), message); | |
for(int j = 0; j != n ; ++j) | |
wait(NULL); | |
} | |
else{ // hijos | |
char buffer_in[BUFFER]; | |
int n2 = read(fd[i][0], &buffer_in, BUFFER); | |
buffer_in[n2] = '\0'; | |
printf("[Hijo: %d - (%d)]: Recibí un mensaje: %s\n", (i+1), getpid(), buffer_in); | |
usleep(100); | |
write(fd[i + 1][1], &buffer_in, BUFFER); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment