sdvferreira
Power Member
viva aqui vai um código para filas de mensagem ....
para ajudar quem tiver a dar esta matéria
espero que gostem ...
para ajudar quem tiver a dar esta matéria
espero que gostem ...
Código:
/*
um pai manda uma msg para um filho e para o filho 2
*/
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/msg.h>
#include <errno.h>
#include <sys/ipc.h>
struct mymsg
{
long mtype;
char msg[20];
};
int main(){
key_t msgid;
int pid;
msgid = msgget(IPC_PRIVATE, IPC_CREAT | 0660);
if(msgid < 0){
printf("Erro ao criar a fila de mensagens");
return 0;
}
pid = fork();
if(pid < 0){
printf("Erro ao criar o processo");
msgctl(msgid, IPC_RMID, NULL);
return -1;
}
if(pid == 0){
struct mymsg tipo;
ssize_t size = msgrcv(msgid, &tipo, sizeof(tipo), 1, 0);
printf("%s", tipo.msg);
}else{
pid = fork();
if(pid == 0){
struct mymsg tipo;
ssize_t size = msgrcv(msgid, &tipo, sizeof(tipo), 2, 0);
printf("%s", tipo.msg);
}else{
struct mymsg msg;
msg.mtype = 1;
strcpy(msg.msg, "filho 1 !\0");
msgsnd(msgid, &msg, sizeof(msg)-sizeof(long), 0);
msg.mtype = 2;
strcpy(msg.msg, "filho 2!\0");
msgsnd(msgid, &msg, sizeof(msg)-sizeof(long), 0);
msgctl(msgid, IPC_RMID, NULL);
}
}
return 1;
}
Última edição: