#include #include #include #include #include #define SIZE 10 #define KEY 0x123456 #define PERMS IPC_CREAT | 0600 struct misDatos { int cin; // Input position in buffer int cout; // Output position in buffer int counter; // Items in buffer char buffer[ SIZE ]; // buffer }; int main( int argc, char ** argv ) { int id; struct misDatos * x; int size = sizeof( struct misDatos ); srandom( time( NULL ) ); id = shmget( KEY, size, PERMS ); x = (struct misDatos *) shmat( id, NULL, 0 ); x->cin = 0; x->cout = 0; x->counter = 0; if ( fork() ) { consumer( x ); } else { producer( x ); } shmctl( id, IPC_RMID, NULL ); } int producer( struct misDatos * p ) { int i, j; int t; for ( i = 0; i < 23; i++ ) { sleep( random() % 2 ); while ( p->counter >= SIZE ) { printf( "productor esperando por espacio en el buffer ...\n" ); sleep( random() % 2 ); } p->buffer[ p->cin++ ] = 'A' + i; p->cin %= SIZE; p->counter++; printf( "item producido [%c] counter = %d \n", 'A' + i, p->counter ); } exit( 0 ); } int consumer( struct misDatos * c ) { int i, j; int t; for ( i = 0; i < 23; i++ ) { sleep( random() % 5 ); while ( c->counter <= 0 ) { printf( "consumidor esperando por datos ...\n" ); } printf( "Item consumido = %c \n", c->buffer[ c->cout++ ] ); c->cout %= SIZE; c->counter--; } }