我刚刚在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

最佳答案

您的错误来自以下行:

if (msgqid = msgget(key, 0666) == FAILED) {

应该是
if ((msgqid = msgget(key, 0666)) == FAILED) {

在第一种情况下,由于operator priority,在分配之前进行比较(==)。
在第二种情况下,paranthesis告诉编译器必须先做什么。

关于c - 错误:参数无效;在发送msgsnd()消息时;与队列ID不匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47305128/

10-12 17:38
查看更多