Created
December 28, 2021 06:48
-
-
Save vicentematus/49086bcc30b42a9b26c5b60388b5bd89 to your computer and use it in GitHub Desktop.
Ejemplo de pipes
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 <stdlib.h> | |
#include <stdio.h> | |
#include <unistd.h> | |
#include <time.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
int main(int argc, char *argv[]) | |
{ | |
//creamos las pipes | |
// p1[0] == READ | |
// p1[1] == WRITE | |
int p1[2]; //Child to parent. | |
int p2[2]; // Parent to Child | |
if (pipe(p1) == -1) | |
{ | |
return 1; | |
} | |
if (pipe(p2) == -1) | |
{ | |
return 1; | |
} | |
int pid = fork(); | |
if (pid == -1) | |
{ | |
return 2; | |
} | |
if (pid == 0) | |
{ | |
// No necesitamos esa pipe abierta ya que solo necesitamos la del parent | |
close(p1[0]); | |
//No necesitamos tampoco esta pipe que escribe al hijo | |
close(p2[1]); | |
//Estamos en el proceso hijo | |
//Queremos leer la data del proceso padre | |
int x; | |
//Eso para leer la data del proceso padre | |
if (read(p2[0], &x, sizeof(x)) == -1) | |
{ | |
printf("Hubo un error en la conexion"); | |
return 0; | |
} | |
printf("El proceso hijo leyo %d\n", x); | |
x *= 4; | |
//ESto es para escribir la data al proceso padre | |
if (write(p1[1], &x, sizeof(x)) == -1) | |
{ | |
printf("Hubo un error en la conexion"); | |
return 0; | |
} | |
printf("El proceso hijo escribio %d\n", x); | |
//Cerramos las pipes restantes. Por descarte vemos las que no necesitamos al inicio. | |
close(p1[1]); | |
close(p2[0]); | |
} | |
else | |
{ | |
close(p1[1]); | |
close(p2[0]); | |
//Proceso Padre | |
srand(time(NULL)); | |
int y = rand() % 10; | |
//p2[1] es el que le envia informacion al proceso hijo | |
if (write(p2[1], &y, sizeof(y)) == -1) | |
{ | |
printf("Hubo un error"); | |
return 0; | |
} | |
printf("El proceso padre escribio %d\n", y); | |
if (read(p1[0], &y, sizeof(y)) == -1) | |
{ | |
printf("Hubo un error"); | |
return 0; | |
} | |
printf("El proceso padre leyo %d\n", y); | |
//Esto es para cerrar todas las pipes y asi no queda ninguna abierta | |
close(p1[0]); | |
close(p2[1]); | |
wait(NULL); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment