简体   繁体   English

处理与消息队列的通信

[英]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. 在我要编写的服务器程序中,我需要在使用fork函数创建的两个进程之间进行通信。 I am receiving an Invalid Argument error but I don't know why. 我收到Invalid Argument错误,但不知道为什么。 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? 我要纠正什么才能使其正常工作?

PS I've even tried to use a sleep function to wait for the child process but it doesn't help. PS我什至尝试使用睡眠功能来等待子进程,但这无济于事。

msgrcv/msgsnd takes an integer msqid returned from msgget not the key. msgrcv/msgsnd采用从msgget返回的整数msqid 而不是密钥。

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. 请记住, data结构应包括一个long msgtype作为您设置的第一个字段,在这种情况下,大概是msgtype = 500,因为这是您要读取的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM