Last active
December 24, 2015 05:39
-
-
Save OscardR/6751458 to your computer and use it in GitHub Desktop.
Imprime N tablas de multiplicar calculadas en paralelo por N procesos.
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> | |
/* Estructura para crear un array de tuberías */ | |
typedef struct tubo { | |
int p[2]; | |
} tubo; | |
int main( int argc, char *argv[] ) { | |
int n = atoi( argv[1] ); | |
int i, j, dato, estado, fd[ 2 ]; | |
tubo tubos[ n ]; | |
for ( i = 1; i <= n; i++ ) { | |
/* Crear una tubería para que el siguiente proceso escriba los resultados */ | |
pipe( tubos[ i - 1 ].p ); | |
/* Usamos un alias para la tubería */ | |
fd[ 0 ] = tubos[ i - 1 ].p[ 0 ]; | |
fd[ 1 ] = tubos[ i - 1 ].p[ 1 ]; | |
if ( fork() == 0 ) { /* Soy el hijo */ | |
/* Escribimos el pid en la tubería */ | |
dato = getpid(); | |
write( fd[ 1 ], & dato, sizeof( dato ) ); | |
/* Escribir los resultados en la tubería */ | |
close( fd[ 0 ] ); | |
for ( j = 1; j <= 10; j++ ) { | |
dato = i * j; | |
write( fd[ 1 ], & dato, sizeof( dato ) ); | |
} | |
close( fd[ 1 ] ); | |
exit( 0 ); | |
} /* if */ | |
} /* for */ | |
/* Leemos las tuberías en orden */ | |
for ( i = 1; i <= n; i++ ) { | |
/* Usamos un alias para la tubería */ | |
fd[ 0 ] = tubos[ i - 1 ].p[ 0 ]; | |
fd[ 1 ] = tubos[ i - 1 ].p[ 1 ]; | |
read( fd[ 0 ], & dato, sizeof( dato ) ); | |
printf( "\n\nTabla del %d [proceso %d]\n--------------------------\n\n", i, dato ); | |
/* Leer los resultados de la tubería */ | |
close( fd[ 1 ] ); | |
int j = 1; | |
while ( read( fd[ 0 ], & dato, sizeof( dato ) ) > 0 ) { | |
printf( "%d×%d = %d\n", i, j, dato ); | |
j++; | |
} | |
close( fd[ 0 ] ); | |
} | |
/* Esperar a todos los procesos */ | |
for ( i = 1; i <= n; i++ ) | |
wait( &estado ); | |
exit( 0 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment