#include #include #define MAX 1000 struct fila { char v[MAX]; int head, tail; sem_t full, empty, mutex; }; /************************ Buffer circular ************************/ void init(struct fila *f) { f->head = 0; f->tail = 0; } void add(struct fila *f, char c) { f->v[f->head] = c; f->head++; if(f->head >= MAX) f->head = 0; } char delete(struct fila *f) { char c = f->v[f->tail]; f->tail++; if(f->tail >= MAX) f->tail = 0; return c; } /***************************** Fila *****************************/ struct fila *criar_fila() { struct fila *f; int id = shmget(IPC_PRIVATE, sizeof(struct fila), IPC_CREAT|0660); if(id < 0) { perror("shmget falhou."); exit(1); } f = shmat(id, NULL, 0); if(f < 0) { perror("shmat falhou."); exit(1); } sem_init(&f->mutex, 1, 1); sem_init(&f->empty, 1, 0); sem_init(&f->full, 1, MAX); init(f); return f; } char tirar_fila(struct fila *f) { sem_wait(&f->empty); sem_wait(&f->mutex); char c = delete(f); sem_post(&f->mutex); sem_post(&f->full); return c; } void por_fila(struct fila *f, char elem) { sem_wait(&f->full); sem_wait(&f->mutex); add(f, elem); sem_post(&f->mutex); sem_post(&f->empty); }