#include #include #include #include #include #define BUF_SIZE 5 #define SHARED_MEM_SIZE (BUF_SIZE+2)*sizeof(int) 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+1)*sizeof(int); *in = *out = 0; pid = fork(); if (pid == 0) { /* consumatore*/ for (i = 0; i < 20; i++) { while (*in == *out) ; value = buffer[*out]; /* leggo il buffer */ *out = (*out + 1) % BUF_SIZE; printf ("\tleggo buf[%d] == %d\n", *out, value); } } else { /* produttore */ for (j = 0; j < 20; 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); } wait (pid); } exit (0); }