我刚刚在 linux 上学习 IPC,并想出了三个简单的程序。一种是创建(并在功能中管理)消息队列。第二个应该只是将消息发送到第一个创建的队列。第三个程序是从队列中接收数据。
所有程序都从同一个根目录继承,并根据源代码和二进制文件插入到单独的目录中。
所以让我们只专注于创建和发送部分,这也将帮助我修复第三个程序。
添加队列 main.c:
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define FAILED -1
int main(int argc, char *argv[]) {
// message data
key_t key;
int msgqid;
if ((key = ftok("../src/main.c", 'Z')) == FAILED) {
perror("ftok");
exit(1);
}
if ((msgqid = msgget(key, 0666 | IPC_CREAT)) == FAILED) { /* create an message queue with owner & group & others permission set to rw- */
perror("msgget");
exit(1);
}
printf("Message Queue %i with key %i, been created [press return to delete]", msgqid, key);
getchar();
if (msgctl(msgqid, IPC_RMID, NULL) == FAILED) {
perror("msgctl");
exit(1);
}
printf("I'm outta here! \n");
return 0;
}
发送 main.c:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/msg.h>
#include <stddef.h>
#include <string.h>
#include "../../lib/shared_msgbuf.h" /* mbuf, MSGSZ */
#define FAILED -1
int main(void) {
char s[MSGSZ];
printf("Enter a message: ");
if (fgets(s, sizeof s, stdin) == NULL)
perror("fgets");
else
strcpy(mbuf.mtext, s);
printf("Connecting to the queue... \n", s);
// Setup
key_t key;
int msgqid;
if ((key = ftok("../../adqueue/src/main.c", 'Z')) == FAILED) {
perror("ftok");
exit(1);
}
if (msgqid = msgget(key, 0666) == FAILED) {
perror("msget");
exit(1);
}
printf("\n*CONNECTION ESTABLISHED* \n");
printf("queue id: %i \n", msgqid);
printf("queue key: %d \n", key);
printf("message: %s \n", s);
printf("Sending the message... \n");
if (msgsnd(msgqid, &mbuf, MSGSZ, 0) == FAILED) {
perror("msgsnd");
exit(0);
}
return 0;
}
所以问题是我Invalid argument
在尝试发送消息时收到错误号。查看数据,我不明白为什么 id 不匹配,因为与队列的连接似乎有效......
示例数据:
./cadqueue
Message Queue 327680 with key 1510081535, been created [press return to delete]
./send
Enter a message: test
Connecting to the queue...
*CONNECTION ESTABLISHED*
queue id: 0
queue key: 1510081535
message: test
Sending the message...
msgsnd: Invalid argument