消息队列不接受 0 作为参数
Message queue doesn't accept 0 as an argument
所以程序是这样运行的。有一个生产者和 4 个消费者。生产者生成 6 个随机数,并通过消息队列将它们发送给 4 个消费者。每个消费者收到它们,并立即
在终止之前,应该通过另一个队列发送一条 mayproduce=0 的消息; mayproduce 是一个整数。
有问题的函数是:
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
我用这样的函数发送mayproduce
msgsnd(qid,&mayproduce,sizeof(int),0)
当我编译它时说 "Invalid argument"。
如果我将 mayproduce 更改为其他数字,对于 mayproduce=2,程序运行正常。
有谁知道它不接受 0 作为参数的原因吗?
代码示例:
mayproduce=2; // if I put 0 here it doesn't work
if(msgsnd(msq2,&mayproduce,tamanho,0)<0) {
perror("\nConsumidor:Erro ao enviar a mensagem: ");
exit(1);
}
msgsnd() 文档指出:
The msgp argument is a pointer to a caller-defined
structure of the following general form:
struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[1]; /* message data */
};
联机帮助页包含更多信息,您需要非常非常仔细地阅读。
所以你真的不应该发送一个指向 int 的指针。您应该创建自己的结构,其中 1. 成员的类型为 long
,并用作消息类型鉴别符,接收方可以查看它以确定它收到的消息类型。
您传递给 msgsend() 的大小是您在 mtype
成员之后发送的所有内容的大小。
当您执行 msgsnd(qid,&mayproduce,sizeof(int),0)
时,会发生以下情况:
-
mayproduce
int 被解释为 struct msgbuf
中的 mtype
成员,正如文档所说,它不能是 0
- sizeof(int) 表示除了
long msgtype
之外你还会有一个 int。但是您的 &mayproduce
指针仅指向一个 int,因此您可能还会发送从堆栈中获取的垃圾值。
你应该这样做:
struct MyMsg {
long mtype;
int mayproduce;
};
struct MyMsg msg;
msg.mtype = 1; //or whatever you want > 0
msg.mayproduce = ....; //whatever you want to send.
size_t msgsize = sizeof(struct MyMsg) - sizeof(long);
msgsnd(msq2,&msg,msgsize,0);
所以程序是这样运行的。有一个生产者和 4 个消费者。生产者生成 6 个随机数,并通过消息队列将它们发送给 4 个消费者。每个消费者收到它们,并立即 在终止之前,应该通过另一个队列发送一条 mayproduce=0 的消息; mayproduce 是一个整数。
有问题的函数是:
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
我用这样的函数发送mayproduce
msgsnd(qid,&mayproduce,sizeof(int),0)
当我编译它时说 "Invalid argument"。
如果我将 mayproduce 更改为其他数字,对于 mayproduce=2,程序运行正常。
有谁知道它不接受 0 作为参数的原因吗?
代码示例:
mayproduce=2; // if I put 0 here it doesn't work
if(msgsnd(msq2,&mayproduce,tamanho,0)<0) {
perror("\nConsumidor:Erro ao enviar a mensagem: ");
exit(1);
}
msgsnd() 文档指出:
The msgp argument is a pointer to a caller-defined structure of the following general form: struct msgbuf { long mtype; /* message type, must be > 0 */ char mtext[1]; /* message data */ };
联机帮助页包含更多信息,您需要非常非常仔细地阅读。
所以你真的不应该发送一个指向 int 的指针。您应该创建自己的结构,其中 1. 成员的类型为 long
,并用作消息类型鉴别符,接收方可以查看它以确定它收到的消息类型。
您传递给 msgsend() 的大小是您在 mtype
成员之后发送的所有内容的大小。
当您执行 msgsnd(qid,&mayproduce,sizeof(int),0)
时,会发生以下情况:
-
mayproduce
int 被解释为struct msgbuf
中的mtype
成员,正如文档所说,它不能是 0 - sizeof(int) 表示除了
long msgtype
之外你还会有一个 int。但是您的&mayproduce
指针仅指向一个 int,因此您可能还会发送从堆栈中获取的垃圾值。
你应该这样做:
struct MyMsg {
long mtype;
int mayproduce;
};
struct MyMsg msg;
msg.mtype = 1; //or whatever you want > 0
msg.mayproduce = ....; //whatever you want to send.
size_t msgsize = sizeof(struct MyMsg) - sizeof(long);
msgsnd(msq2,&msg,msgsize,0);