Last active
August 29, 2015 13:56
-
-
Save dlion/9306447 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Autore: Domenico Luciani | |
* Data: 28/02/14 | |
* Esercizio: 2 | |
* CFU: 9 | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#include <signal.h> | |
void signNew() { } //Nuova funzione del sigHandler | |
int main(int argc, char **argv) | |
{ | |
int **M, //matrice | |
n, m, //righe, colonne | |
i, j, //counter | |
somma=0, //Somma | |
fd[2]; //File Descriptor | |
pid_t pid; //pid | |
void (*signOld)(int), //Vecchio signal | |
(*signOld1)(int); //Vecchio signal1 | |
if(argc != 3 || (atoi(argv[1]) % 2) != 0) | |
{ | |
printf("usage: %s <n> <m>\n<n> pari\n",argv[0]); | |
return -1; | |
} | |
n = atoi(argv[1]); //righe | |
m = atoi(argv[2]); //colonne | |
// Ridefinisco i signalHandler | |
signOld = signal(SIGINT, signNew); | |
signOld1 = signal(SIGSTOP, signNew); | |
//Alloco la matrice e la popolo | |
M = (int**)malloc(n*sizeof(int*)); | |
for(i=0; i < n; i++) | |
{ | |
M[i] = (int*)malloc(m*sizeof(int)); | |
for(j=0; j < m; j++) | |
{ | |
printf("Inserisci il valore contenuto in %d-%d: ",i,j); | |
scanf("%d",&M[i][j]); | |
} | |
} | |
if(pipe(fd) < 0) | |
{ | |
puts("Errore nella pipe!"); | |
return -1; | |
} | |
for(i=0; i < n; i++) | |
{ | |
switch(pid = fork()) | |
{ | |
case -1: //Errore | |
puts("Errore nella fork!"); | |
return -1; | |
break; | |
case 0: // Sono il figlio | |
for(j=0; j < m; j++) | |
somma += M[i][j]; | |
close(fd[0]); | |
write(fd[1], &somma, sizeof(int)); | |
exit(1); | |
break; | |
default: | |
wait(NULL); | |
} | |
} | |
close(fd[1]); | |
for(i=0; i < n; i++) | |
{ | |
read(fd[0], &j, sizeof(int)); | |
printf("Somma parziale della riga %d: %d\n", i, j); | |
somma += j; | |
} | |
printf("La media della matrice e': %f\n",somma,(double)somma/(n*m)); | |
//Rimetto i signalHandler a posto | |
signal(SIGINT, signOld); | |
signal(SIGSTOP, signOld1); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment