我想使用POSIX消息队列创建服务器和多个客户端应用程序。这是我的客户端简化代码。我删除了字符串,内存和其他操作,只是为了简单说明。
客户端:
// Set attributes of client queue
attr.mq_flags = 0;
attr.mq_maxmsg = 10;
attr.mq_msgsize = MSG_SIZE;
attr.mq_curmsgs = 0;
// Create client queue
mq_client = mq_open(sqname_client, O_CREAT | O_RDONLY, 0644, &attr);
// Open server queue
mq_server = mq_open(sqname_server, O_WRONLY);
// Send message to the server
mq_send(mq_server, message, MSG_SIZE, 0);
// Wait for receiving a message back from server
while (1)
{
bytes_read = mq_receive(mq_client, message, MSG_SIZE, NULL);
message[bytes_read] = '\0';
printf("\nMessage from server to client: %s\n",message);
}
// Clean-up
mq_close(mq_server);
mq_unlink(sqname_client);
mq_close(mq_client);
服务器:
// Set attributes of server queue
attr.mq_flags = 0;
attr.mq_maxmsg = 10;
attr.mq_msgsize = MSG_SIZE;
attr.mq_curmsgs = 0;
// Create the server queue
mq_server = mq_open(sqname_server, O_CREAT | O_RDONLY, 0644, &attr);
// Wait for receiving a message from the client
while (1)
{
ssize_t bytes_read;
bytes_read = mq_receive(mq_server, message, MSG_SIZE, NULL);
// Send the respond through the client's message queue
mq_client = mq_open(sqname_client, O_WRONLY);
mq_send(mq_client, "I got your message client", MSG_SIZE, 0);
}
// Clean-up
mq_close(mq_server);
mq_close(mq_client);
mq_unlink(sqname_server);
这非常适合从客户端向服务器发送消息。但服务器对客户端的响应不会出现在客户端。可能是什么原因?