首页 > 解决方案 > 在消息队列linux c中发送不同类型的消息

问题描述

我有这样的代码:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define MAXLINE 1024

struct my_msgbuf {
        long mtype;
        char mtext[MAXLINE];
};
int main(void)
{
    struct my_msgbuf buf;
    int msqid;
    key_t key;

    if ((key = ftok("client.c", 'B')) == -1) {
        perror("ftok");
        exit(1);
    }

    if ((msqid = msgget(key, 0644 | IPC_CREAT)) == -1) {
        perror("msgget");
        exit(1);
    }

    printf("Write a text:\n");

    buf.mtype = 1; 
    while( fgets(buf.mtext, MAXLINE, stdin) != NULL ) {
        if (msgsnd(msqid, (struct msgbuf *)&buf, sizeof(buf), 0) == -1)
            perror("msgsnd");
    }

    if (msgctl(msqid, IPC_RMID, NULL) == -1) {
        perror("msgctl");
        exit(1);
    }

    return 0;
}

此代码使用 linux (c) 中的 ipc 消息队列发送消息,但它发送的消息类型等于“1”。我必须发送消息,但每条消息都必须具有不同的类型。我删除了“while”,只留下 fgets。没有“while”的 fget 将一直工作到新行或到达 MAXLINE。它不起作用。我想达到这样的效果:

写一个类型:
1(我)
写一个文本:
第一条消息(我)
写一个类型:
2(我)
写一个文本:
第二条消息(我)
....

编译并运行程序后,我到达:

写一个类型:
1(我)
写一个文本:
写一个类型:
2(我)
写一个文本:
写一个类型:
....

这是我修改后的代码。它出什么问题了?

#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define MAXLINE 1024

struct my_msgbuf {
        long mtype;
        char mtext[MAXLINE];
};

int main(void)
{
    struct my_msgbuf buf;

    int msqid;
    key_t key;

    if ((key = ftok("client.c", 'B')) == -1) {
        perror("ftok");
        exit(1);
    }

    if ((msqid = msgget(key, 0644 | IPC_CREAT)) == -1) {
        perror("msgget");
        exit(1);
    }
while(1){
        printf("Write a type:\n");
        scanf("%ld", &buf.mtype);
        printf("Write a text:\n");
        fgets(buf.mtext, MAXLINE, stdin);

        if (msgsnd(msqid, (struct msgbuf *)&buf, sizeof(buf), 0) == -1){
            perror("msgsnd");
        }
}

    if (msgctl(msqid, IPC_RMID, NULL) == -1) {
        perror("msgctl");
        exit(1);
    }

    return 0;
}```









标签: clinuxmessage-queue

解决方案


推荐阅读