我在使用我的代码时遇到了一些麻烦。它应该创建一个消息队列并发送消息,而不是等待另一个程序接收该消息并回答。问题是,当我运行它时,我在msgsnd和msgrcv上都得到了一个无效的参数。消息队列给了我一个无效的参数
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/msg.h>
typedef struct my_msg{
long type;
char text[100];
char sqdr;
}message;
static void score(int messagge_id, char* A_B){
message send;
send.type=1;
strcpy(send.text, "Try to score");
send.sqdr = *A_B;
if((msgsnd(messagge_id, &send, sizeof(send), 0))<0)perror("Error msgsnd\n");
sleep(3);
if((msgrcv(messagge_id, &send, sizeof(send), 4, 0))==-1)perror("Error msgrcv 1\n");
int test=atoi(send.text);
printf("%d\n", test);
}
int main(){
int caso, key;
char team= 'A';
key=1234;
int msg_id=msgget(key, S_IRUSR|S_IWUSR);
printf("Try function score\n");
score(msg_id, &team);
printf("After score\n");
return 0;
}
为什么你不错误检查'msgget()'调用?它成功了吗?是否有另一个进程创建了消息队列? –
我会尝试检查msgget,但我认为问题不在于创建消息队列,因为我没有编写第二个程序。它可能是使用的关键问题吗? – Leo
我认为这很可能是因为您没有使用密钥'IPC_PRIVATE'或指定'IPC_CREAT'作为标记(以及'S_IRUSR | S_IWUSR'),因此您没有附加到预先存在的消息队列,并没有创建它。参见['msgget()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/msgget.html)(和 ['msgctl()'](http://pubs.opengroup.org/ onlinepubs/9699919799/functions/msgctl.html)在完成后删除消息队列)。请注意,一旦队列被创建,它将一直存在直到被删除。 –