System V 消息队列 - 获取已经存在的消息

System V Message Queues - getting message that already exists

我一直在做一个项目,我必须做的任务之一是将从另一个进程接收的字符串通过管道传递到另一个进程,但这次我必须使用消息队列。

我已经设法了解 msgqueue 的工作原理并制作了一个简单的工作程序,但问题是,它在从 stdinfgets 接收字符串时工作。

我的问题是:

我可以传递一个已经保存在其他变量中的字符串吗(例如 char s[20] = "message test"; ) 到消息队列多行文本?

我的简单程序是这样的:

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

struct msgbuf {
    long    mtype;         
    char string[20];
};
struct msgbuf mbuf;
int open_queue( key_t keyval ) {
    int     qid;

    if((qid = msgget( keyval, IPC_CREAT | 0660 )) == -1)
        return(-1);

    return(qid);
}

int send_message( int qid){
    int result, size;



    size = sizeof mbuf.string;
    if((result = msgsnd( qid, &mbuf, size, 0)) == -1)
          return(-1);

    return(result);
}

int remove_queue( int qid ){
    if( msgctl( qid, IPC_RMID, 0) == -1)
        return(-1);

    return(0);
}

int read_message( int qid, long type){
    int     result, size;


    size = sizeof mbuf.string;      

    if((result = msgrcv( qid, &mbuf, size, type,  0)) == -1)
        return(-1);

    return(result);
}

int main(void){
    int    qid;
    key_t  msgkey;
    msgkey = ftok(".", 'm');
    if(( qid = open_queue( msgkey)) == -1) {
        perror("openErr");
        exit(1);
    }

    mbuf.mtype   = 1; 
    fgets(mbuf.string, sizeof mbuf.string, stdin);

    if((send_message( qid)) == -1) {
        perror("sendErr");
        exit(1);
    }


    mbuf.mtype   = 1;       

    if((read_message(qid, mbuf.mtype))== -1){
        perror("recERR");
        exit(1);
    }
    printf("Queue: %s\n", mbuf.string);
    remove_queue(qid);

    return 0;
}

您的代码使用 fgets() 用从标准输入读取的输入填充缓冲区 mbuf.string。您可以改用 strcpy(mbuf.string, "message test") 之类的东西,您可以在其中传递变量或使用硬编码字符串。

我建议使用 POSIX 消息队列 API,因为系统 V API 已弃用。