我正在对消息队列进行第一次练习。我希望 mq_receive 阻塞,所以我没有打开 O_NOBLOCK。
mq_receive 方法正在返回,并且 perror() 正在打印“消息太长”。这是在我发送消息之前。
ATM 发送消息:
void* run_ATM(void* arg) {
int status;
char accountNumber[15];
cout << "ATM is running" << endl;
cout << "Please input an account number > ";
cin >> accountNumber;
status = mq_send(PIN_MSG, accountNumber, sizeof(accountNumber), 1);
}
数据库接收它们
void* run_DB(void* arg){
cout << "Database server running" << endl;
int status;
char received_acct_number[30];
while(1){
status = mq_receive(PIN_MSG, received_acct_number, 100, NULL);
if (status < 0){
perror("error ");
} else {
cout << "received account number\t" << received_acct_number << endl;
}
}
}
这只是初步代码 - 所以它最终会做更多的事情。我只是想得到一个基本的工作示例。
编辑:让它运行所需的其他代码:
#define PIN_MSG_NAME "/pin_msg"
#define DB_MSG_NAME "/db_msg"
#define MESSAGE_QUEUE_SIZE 15
pthread_t ATM;
pthread_t DB_server;
pthread_t DB_editor;
void* run_ATM(void* arg);
void* run_DB(void* arg);
static struct mq_attr mq_attribute;
static mqd_t PIN_MSG, DB_MSG;
int main(int argc, char const *argv[])
{
pthread_attr_t attr;
mq_attribute.mq_maxmsg = 10; //mazimum of 10 messages in the queue at the same time
mq_attribute.mq_msgsize = MESSAGE_QUEUE_SIZE;
PIN_MSG = mq_open(PIN_MSG_NAME, O_CREAT | O_RDWR, 0666, &mq_attribute);
DB_MSG = mq_open(DB_MSG_NAME, O_CREAT | O_RDWR, 0666, &mq_attribute);
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 1024*1024);
long start_arg = 0; //the start argument is unused right now
pthread_create(&ATM, NULL, run_ATM, (void*) start_arg);
pthread_create(&DB_server, NULL, run_DB, (void*) start_arg);
pthread_join(ATM, NULL);
pthread_join(DB_server, NULL);
}
接收缓冲区大于消息队列大小,应该没有问题吧?
最佳答案
如果您检查函数的错误返回并打印它们,错误将是显而易见的。您正在将 accountNumber
和 PIN
的值 转换为指针,而不是转换它们的地址。你想要:
status = mq_send(PIN_MSG, (const char*) &accountNumber, MESSAGE_QUEUE_SIZE, 1);
status = mq_send(PIN_MSG, (const char*) &PIN, MESSAGE_QUEUE_SIZE, 1);
status = mq_receive(PIN_MSG, (char*) &received_acct_number, 100, NULL);
status = mq_receive(PIN_MSG, (char*) &received_PIN, MESSAGE_QUEUE_SIZE, NULL);
请注意,我们的代码仍然存在很多问题,最明显的是您没有正确处理这些变量的大小而使它们溢出。您可以像这样修复它:
status = mq_send(PIN_MSG, (const char*) &accountNumber, sizeof (accountNumber), 1);
status = mq_send(PIN_MSG, (const char*) &PIN, sizeof (PIN), 1);
status = mq_receive(PIN_MSG, (char*) &received_acct_number, sizeof(received_acct_number), NULL);
status = mq_receive(PIN_MSG, (char*) &received_PIN, sizeof(received_PIN), NULL);
但实际上你应该有某种消息格式,你应该将你的消息序列化为这种格式。
关于c++ - mq_receive 消息太长 - 没有发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40985967/