簡體   English   中英

C IPC-無法從隊列接收消息

[英]C IPC - cannot receive message from queue

我用C編寫了一個使用IPC消息隊列的簡單程序,但是將其作為指針發送時卻無法收到消息。

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <error.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <ctype.h>
#include <string.h>

typedef struct Message {
    long type;
    char content[16];
} Message;

int main(int argc, char* argv[]) {

    printf("Starting...\n");
    key_t key = 1;
    Message* msg = malloc(sizeof(Message));
    int msg_id = msgget(key, IPC_CREAT | 0777);
    printf("ID of the created queue: %d\n", msg_id);
    strcpy(msg->content, "Hello");
    msgsnd(msg_id, msg, 16, 0);
    free(msg);

    if (fork() == 0) {
        int msgid = msgget(key, 0);
        printf("Message queue id: %d\n", msgid);
        Message rcvMsg;
        msgrcv(msgid, &rcvMsg, 16, 0, 0);
        printf("Received: %s\n", rcvMsg.content);

        if (msgctl(msgid, IPC_RMID, 0) != 0) {
            perror("Cannot remove queue from system.\n");
            exit(1);
        }

        exit(0);
    }

    wait(NULL);
    printf("Stop.\n");
    exit(0);
}

我得到的輸出是:

Starting... ID of the created queue: 327680 Message queue id: 327680

程序正在等待。 但是,當我將消息作為標准變量(而不是結構指針)發送時,消息就被傳遞了。

工作程序:

int main(int argc, char* argv[]) {

    printf("Starting...\n");
    key_t key = 1;
    Message msg;
    int msg_id = msgget(key, IPC_CREAT | 0777);
    printf("ID of the created queue: %d\n", msg_id);
    strcpy(msg.content, "Hello");
    msgsnd(msg_id, &msg, 16, 0);

    if (fork() == 0) {
        int msgid = msgget(key, 0);
        printf("Message queue id: %d\n", msgid);
        Message rcvMsg;
        msgrcv(msgid, &rcvMsg, 16, 0, 0);
        printf("Received: %s\n", rcvMsg.content);

        if (msgctl(msgid, IPC_RMID, 0) != 0) {
            perror("Cannot remove queue from system.\n");
            exit(1);
        }

        exit(0);
    }

    wait(NULL);
    printf("Stop.\n");
    exit(0);
}

該程序返回預期的輸出:

Starting... ID of the created queue: 327680 Message queue id: 327680 Received: Hello Stop.

這是怎么回事? 怎么了? 如何調試呢?

還有一個問題是創建結構變量的最佳方法是什么-指針還是不指針(順便說一句,非結構指針變量的名稱是什么?)?

Message msg; Message* msg = malloc(sizeof(Message));

您沒有初始化消息的type字段。 msgsnd要求類型字段具有正整數值。

您應該更改代碼,以便它檢查每個函數的返回值和返回值。 我通過更改msgsnd(msg_id, msg, 16, 0);發現了此錯誤msgsnd(msg_id, msg, 16, 0); int result = msgsnd(msg_id, msg, 16, 0); 然后插入:

if (result == -1)
{
    perror("msgsnd");
    exit(EXIT_FAILURE);
}

這告訴我msgsnd的參數無效,因此我查看了其文檔,發現該type必須為正。

您還應該檢查msgrcv的返回值。

對於這樣的小型結構,除非需要在創建它的函數退出后該結構繼續存在,否則不需要malloc 如果一個函數只是要使用一個消息結構並丟棄它,請在本地聲明它。 如果函數要向其調用方返回消息結構,請使用malloc對其進行分配並返回一個指針。 (然后,調用者負責通過將其指針傳遞給free來稍后釋放它。)

暫無
暫無

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

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