PatLas
PatLas

Reputation: 189

Process communication with message queue

I have a problem with a communication queue. In my server program, which I'm trying to write, I need to communicate between two processes created with the fork function. I am receiving an Invalid Argument error but I don't know why. Here is my simplified non-working) code.

key_t key = ftok(".",'A');
msgget(key,IPC_CREAT);
perror(""); //receive succes

if(fork()>0){
    msgbuf dat;

    msgrcv(key,(void*)&dat,(size_t)sizeof(dat),500,0);
    perror(""); //receive INVALID ARGUMENT
    cout<<dat.mtext<<endl;
}
else
{
    msgbuf data;
    data.mtext[0]='a';
    data.mtype=500;

    msgsnd(key,(void*)&data,(size_t)sizeof(data),0);
    perror(""); //receive INVALID ARGUMENT
}

What shall I correct to make it work?

P.S I've even tried to use a sleep function to wait for the child process but it doesn't help.

Upvotes: 0

Views: 803

Answers (1)

Duck
Duck

Reputation: 27572

msgrcv/msgsnd takes an integer msqid returned from msgget not the key.

int qid = msgget(key, IPC_CREAT);

msgrcv(qid, (void*)&data, (size_t) sizeof(data), 500, 0);

//..........

msgsnd(qid,(void*) &dat,(size_t) sizeof(dat), 0);

Remember that the data struct should include a long msgtype as the first field that you set, in this case presumably of msgtype = 500 since that is what you are trying to read.

Upvotes: 1

Related Questions