簡體   English   中英

消息隊列給我一個無效的參數

[英]Message queue is giving me an invalid argument

我的代碼有問題。 它應該創建一個消息隊列並發送一條消息,而不是等待一段時間讓另一個程序接收該消息並進行回答。 問題是,當我運行它時,在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;
}

您需要確保已創建消息隊列。 您可以使用密鑰IPC_PRIVATE或將IPC_CREAT添加到標志。 您還需要嘗試正確閱讀消息。 您發送了“類型1”消息,並試圖讀取“類型4”消息,因此讀取掛起。

此代碼還刪除了消息隊列。 如果它是專用隊列(程序終止時將刪除此類隊列),則並不重要,但對於使用IPC_CREAT和用戶定義的鍵的隊列而言,這一點很重要。 (我還更改了消息文本,以使atoi()返回的結果比零更有趣,更令人信服。代碼還使用了單獨的發送和接收緩沖區,因此我們知道代碼不會欺騙和重用緩沖區中已經存在的數據。)

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/msg.h>
#include <fcntl.h>

typedef struct my_msg
{
    long type;
    char text[100];
    char sqdr;
} message;

static void score(int messagge_id)
{
    message send;
    message recv;
    send.type = 1;
    strcpy(send.text, "47 tries to score");
    send.sqdr = 'A';
    if ((msgsnd(messagge_id, &send, sizeof(send), 0)) < 0)
        perror("Error msgsnd");
    printf("Dozing...\n");
    sleep(3);
    printf("Unslumbering...\n");
    if ((msgrcv(messagge_id, &recv, sizeof(recv), -4, 0)) == -1)
        perror("Error msgrcv");
    int test = atoi(recv.text);
    printf("%d\n", test);
}

int main(void)
{
    int key = 1234;
    int flags = S_IRUSR|S_IWUSR|IPC_CREAT;
    // int key = IPC_PRIVATE;
    // int flags = S_IRUSR|S_IWUSR;
    int msg_id = msgget(key, flags);
    if (msg_id < 0)
        perror("Error msgget");
    else
    {
        printf("Try function score\n");
        score(msg_id);
        printf("After score\n");
        if (msgctl(msg_id, IPC_RMID, 0) < 0)
            perror("Error msgctl");
    }
    return 0;
}

樣本輸出:

Try function score
Dozing...
Unslumbering...
47
After score

當然,在“打zing睡”和“沉睡”之間會有3秒鍾的停頓。

像這樣使用:

if((msgsnd(messagge_id, (void *)&send, sizeof(send), 0))<0)perror("Error msgsnd\n");

if((msgrcv(messagge_id, (void *)&send, sizeof(send), 4, 0))==-1)perror("Error msgrcv 1\n");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM