Created
December 25, 2017 15:24
-
-
Save Jviejo/404f56395ff97a08a4007eeb27e95312 to your computer and use it in GitHub Desktop.
pipe un parent two child, passing integer values
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 <stdlib.h> | |
#include <string.h> | |
#include <sys/types.h> | |
#include <wait.h> | |
void cerrar (int pipe1[2], int pipe2[2]) | |
{ | |
close(pipe1[0]); | |
close(pipe1[1]); | |
close(pipe2[0]); | |
close(pipe2[1]); | |
} | |
int main() | |
{ | |
int pipe1[2]; | |
int pipe2[2]; | |
if (pipe(pipe2) == -1) { | |
perror("bad pipe2"); | |
exit(1); | |
} | |
if (pipe(pipe1) == -1) { | |
perror("bad pipe1"); | |
exit(1); | |
} | |
int child1; | |
int child2; | |
if ((child1 = fork()) == 0) { | |
// este proceso lee del pipe, por eso duplico el 0 | |
dup2(pipe1[0], 0); | |
// va a escribir el en el pipe 1 | |
dup2(pipe2[1], 1); | |
// cierro todos los pipes | |
cerrar(pipe1, pipe2); | |
int n; | |
while (scanf("%d", &n) != EOF) { | |
if (n % 2 != 0) | |
printf("%d\n", n); | |
} | |
exit(0); | |
} | |
if ((child2 = fork()) == 0) { | |
// este proceso lee del pipe2 | |
// el proceso hijo 1 escribe en el pipe | |
dup2(pipe2[0], 0); | |
cerrar(pipe1, pipe2); | |
int n; | |
while (scanf("%d", &n) != EOF) { | |
if (n % 3 != 0) | |
printf("%d\n", n); | |
} | |
exit(0); | |
} | |
if (child1 != 0 && child2 != 0) { | |
// el padre escriben en el pipe1 que lee el hijo 1 | |
dup2(pipe1[1], 1); | |
cerrar(pipe1, pipe2); | |
for (int i = 0; i < 100092; i++) | |
printf("%d\n", i); | |
// importante, si no perdemos información | |
fflush(stdout); | |
// cierro el pipe de escritura | |
close(1); | |
// esparamos | |
int status; | |
wait(&status); | |
wait(&status); | |
exit(0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment