我在使用我的代碼時遇到了一些麻煩。它應該創建一個消息隊列併發送消息,而不是等待另一個程序接收該消息並回答。問題是,當我運行它時,我在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)在完成後刪除消息隊列)。請注意,一旦隊列被創建,它將一直存在直到被刪除。 –