View Full Version : Codigo - uso do fork - pai manda msg para filho 1 e filho 2


sdvferreira
01-06-2007, 16:02
viva aqui vai um código para filas de mensagem ....

para ajudar quem tiver a dar esta matéria

espero que gostem ...




/*
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;
}