// Estrutura que serve como envelope à mensagem a ser colocada nas filas de mensagens // Aproveita-se o campo type para denotar o destinatário da mensagem typedef struct { long type; Mensagem msg; } Pacote; // Assumindo que existem as seguintes filas filaP1 - liga P1 a PA filaP2 - liga P2 a PA filaPAB - liga PA a PB filaP3 - liga PB a P3 filaP4 - liga PB a P4 // Consonte o processo que está a executar, P1 ou P2, assume-se que: // a variável fila contém filaP1 ou filaP2 int enviarMensagem(Mensagem *msg, int p) { if (p != P3 && p != P4) return -1; Pacote pacote; pacote.type = p; memcpy(&pacote.msg, msg, MSIZE); if (msgsnd(fila, &pacote, MSIZE, 0) == -1) return -1; return 0; } // Comportamento de PA int PA() { Pacote pacote; int filaIn = filaP1; while(1) { if (msgrcv(filaIn, &pacote, MSIZE, 0, 0) == -1) return -1; if (msgsnd(filaPAB, &pacote, MSIZE, 0) == -1) return -1; filaIn = filaIn == filaP1 ? filaP2 : filaP1; } } // Comportamento de PB int PB() { Pacote pacote; int filaOut; while(1) { if (msgrcv(filaPAB, &pacote, MSIZE, 0, 0) == -1) return -1; filaOut = pacote.type == P3 ? filaP3 : filaP4; if (msgsnd(filaOut, &pacote, MSIZE, 0) == -1) return -1; } } // Consonte o processo que está a executar, P3 ou P4, assume-se que: // a variável fila contém filaP3 ou filaP4 int receberMensagem(Mensagem *msg, int p) { if (p != P1 && p != P2) return -1; Pacote pacote; if (msgrcv(fila, &pacote, MSIZE, p, 0) == -1) return -1; memcpy(msg, &pacote.msg, MSIZE); return 0; }