hi all...
ive been trying this program where i spawn 4 threads... and i am trying to use message queue to send msgs from 3 of the threads to the parent thread... but it doent seem to be working... ive almost pulled out my hair tryin to fix the prob
another wierd thing is that it worksthe 1st time when i reboot the system then stops workin
also im getting the msgqid=0...
here is the code:
HTML Code:
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<stdlib.h>
#include<errno.h>
struct message
{
int type;
int msg;
};
int main(void)
{
pid_t pid0,pid1,pid_p,pid_c1,pid_c2,pid_c3;
key_t key;
int msgqid;
//extern int errno;
struct message *msgs,*msgr;
pid_p=getpid();
if((key=ftok("abc.txt",'c'))==-1)
perror("Error in ftok\n");
else
printf("Ftok executed.Key=%d\n",key);
if((msgqid=(msgget(key,0666|IPC_CREAT))==-1))
perror("Error creating queue\n");
else
printf("Queue created.MSGQID=%ld\n",msgqid);
pid0=fork();
if(pid0<0)
{
perror("Error in fork\n");
}
pid1=fork();
if(pid1<0)
{
perror("Error in fork\n");
}
if(pid0==0 && pid1==0)
{
pid_c1=getpid();
printf("In child.Process ID=%d\n",pid_c1);
msgs->type=1;
msgs->msg=1;
if(msgsnd(msgqid,&(msgs->type),sizeof(struct message),1)==-1)
{ printf("%d\n",errno);perror("Message not sent.Type 1\n");}
else
printf("Message sent.Type 1\n");
}
if(pid0==0 && pid1!=0)
{
pid_c2=getpid();
printf("In child.Process ID=%d\n",pid_c2);
msgs->type=2;
msgs->msg=2;
if(msgsnd(msgqid,&(msgs->type),sizeof(struct message),2)==-1)
perror("Message not sent.Type 2\n");
else
printf("Message sent.Type 2\n");
}
if(pid0!=0 && pid1==0)
{
pid_c3=getpid();
printf("In child.Process ID=%d\n",pid_c3);
msgs->type=3;
msgs->msg=3;
if(msgsnd(msgqid,&(msgs->type),sizeof(struct message),3)==-1)
perror("Message not sent.Type 3\n");
else
printf("Message sent.Type 3\n");
}
if(pid0!=0 && pid1!=0)
{
wait(NULL);
wait(NULL);
wait(NULL);
printf("In parent.Process ID=%d\n",pid_p);
if(msgrcv(msgqid,&(msgr->type),sizeof(struct message),1,0)==-1)
perror("Message not recvd.Type 1\n");
else
printf("Message revcd.Type 1\n");
if(msgrcv(msgqid,&(msgr->type),sizeof(struct message),2,0)==-1)
perror("Message not recvd.Type 2\n");
else
printf("Message revcd.Type 2\n");
if(msgrcv(msgqid,&(msgr->type),sizeof(struct message),3,0)==-1)
perror("Message not recvd.Type 3\n");
else
printf("Message revcd.Type 3\n");
if(msgctl(msgqid,IPC_RMID,NULL)==-1)
perror("Error removing queue\n");
else
printf("Queue removed\n");
}
exit(0);
}