Skip to content

Instantly share code, notes, and snippets.

@Ts-Pytham
Last active April 24, 2023 14:42
Show Gist options
  • Save Ts-Pytham/b46ca06ab339b473750ca81fcff7a2a3 to your computer and use it in GitHub Desktop.
Save Ts-Pytham/b46ca06ab339b473750ca81fcff7a2a3 to your computer and use it in GitHub Desktop.
Envio de información (estructura) por varias tuberias
#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 ---
^ |
| |
|------------------------|
*/
typedef struct{
int parent;
char data[BUFFER];
} message;
int main(){
int n, i;
printf("Ingrese la cantidad de hijos a crear: \n");
scanf("%d", &n);
if(n < 0){
printf("El valor debe ser mayor o igual a 0!\n");
exit(-1);
}
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
}
}
message msg;
msg.parent = getpid();
printf("[Padre (%d)]: Ingrese una letra sin espacios\n", getpid());
fgets(msg.data, BUFFER, stdin);
write(fd[0][1], &msg, sizeof(message));
usleep(100);
read(fd[n_tuberias - 1][0], &msg, sizeof(message));
if(msg.parent == getpid()){
printf("[Padre (%d)]: Recibí un mensaje: (Padre: %d) %s\n", getpid(), msg.parent, msg.data);
}
else{
printf("[Padre (%d)]: Recibí un mensaje: (Hijo: %d) %s\n", getpid(), msg.parent, msg.data);
}
for(int j = 0; j != n ; ++j)
wait(NULL);
}
else{ // hijos
message msg;
int n2 = read(fd[i][0], &msg, sizeof(message));
msg.data[n2] = '\0';
if(msg.parent == getppid()){
printf("[Hijo: %d - (%d)]: Recibí un mensaje: (Padre: %d) %s\n", (i+1), getpid(), msg.parent, msg.data);
}
else
printf("[Hijo: %d - (%d)]: Recibí un mensaje: (Hijo: %d) %s\n", (i+1), getpid(), msg.parent, msg.data);
usleep(100);
msg.parent = getpid();
write(fd[i + 1][1], &msg, sizeof(message));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment