#include #include #include #include #include #define BUF_SIZE 5 #define SHARED_MEM_SIZE (BUF_SIZE)*sizeof(int) + 2*sizeof(int*) //syncro-5.c int main (void) { int pid, i, j, value; int* shared_memory; int *in; int *out; int *buffer; shared_memory=mmap(0,SHARED_MEM_SIZE,PROT_READ|PROT_WRITE,MAP_ANONYMOUS|MAP_SHARED,-1,0); buffer = (int*) shared_memory; in = (int*) shared_memory + BUF_SIZE*sizeof(int); out = (int*) (shared_memory + BUF_SIZE*sizeof(int) + sizeof(int*)); *in = *out = 0; if ((pid = fork()) == 0) /* consumatore*/ for (i = 0; i < 10; i++) { while (*in == *out) ; value = buffer[*out]; /* leggo il buffer */ *out = (*out + 1) % BUF_SIZE; printf ("\tleggo1 buf[%d] == %d\n", *out, value); } if ((pid = fork()) == 0) /* consumatore*/ for (i = 0; i < 10; i++) { while (*in == *out) ; value = buffer[*out]; /* leggo il buffer */ *out = (*out + 1) % BUF_SIZE; printf ("\t\tleggo2 buf[%d] == %d\n", *out, value); } /* produttore */ for (j = 0; j < 10; j++) { while ((*in + 1) % BUF_SIZE == *out); buffer[*in] = j; /* scrivo il buffer */ *in = (*in + 1) % BUF_SIZE; printf ("ho scritto %d in buf[%d]\n", j, *in); } return(0); }