Skip to content

Instantly share code, notes, and snippets.

@dlion
Created February 27, 2014 18:32
Show Gist options
  • Save dlion/9256025 to your computer and use it in GitHub Desktop.
Save dlion/9256025 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#define N 10
int main(int argc, char **argv)
{
pid_t pid; // fork
int i, j, conto, max=0,
fd[2]; // pipe
char l;
if(argc != 2)
{
printf("Usage: %s <numbers>\n",argv[0]);
return -1;
}
if(pipe(fd) < 0)
{
puts("Errore nella pipe!");
return -1;
}
for(i=0; i < N; i++)
{
switch(pid = fork())
{
case -1:
puts("Errore nella fork!");
exit(-1);
break;
case 0:
//Sono uno dei figli
l = (char)(((int)'0')+i);
conto = 0;
for(j=0; j < strlen(argv[1]); j++)
if(argv[1][j] == l)
conto++;
printf("FIGLIO: La lettera che ho cercato è: %c\n ed ha %d occorrenze\n", l, conto);
close(fd[0]);
write(fd[1], &conto, sizeof(int));
exit(1);
break;
default:
//Sono il padre
wait(NULL);
}
}
close(fd[1]);
for(i=0; i < N; i++)
{
read(fd[0], &conto, sizeof(int));
if(conto > max)
max = i;
printf("PADRE: %d = %d\n", i, conto);
}
printf("Il risultato delle occorrenze maggiore è: %d\n", max);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment