c - C 中的消息队列 : implementing 2 way comm

标签 c linux pointers ipc message-queue

我是一名学生,也是一名 C 语言初学者。我想在 C linux 中使用消息队列实现双向通信。我需要两个队列还是只需要一个队列来完成这项工作?

另外我想知道我可以将数据(在代码中显示)发送到另一个进程还是我需要将其声明为字符数组。

typedef struct msg1
{
    int mlen;
    char *data;
}M1;

typedef struct msgbuf
{
    long    mtype;
    M1      *m;
} message_buf;

提前致谢:)

最佳答案

另外我想知道我可以将数据(在代码中显示)发送到另一个进程还是我需要将其声明为字符数组

是的,你可以将数据发送到另一个进程

喜欢

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE     128

void die(char *s)
{
  perror(s);
  exit(1);
}

struct msgbuf
{
    long    mtype;
    char    mtext[MAXSIZE];
};

main()
{
    int msqid;
    int msgflg = IPC_CREAT | 0666;
    key_t key;
    struct msgbuf sbuf;
    size_t buflen;

    key = 1234;

    if ((msqid = msgget(key, msgflg )) < 0)   //Get the message queue ID for the given key
      die("msgget");

    //Message Type
    sbuf.mtype = 1;

    printf("Enter a message to add to message queue : ");
    scanf("%[^\n]",sbuf.mtext);
    getchar();

    buflen = strlen(sbuf.mtext) + 1 ;

    if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0)
    {
        printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buflen);
        die("msgsnd");
    }

    else
        printf("Message Sent\n");

    exit(0);
}


//IPC_msgq_rcv.c

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE     128

void die(char *s)
{
  perror(s);
  exit(1);
}

typedef struct msgbuf
{
    long    mtype;
    char    mtext[MAXSIZE];
} ;


main()
{
    int msqid;
    key_t key;
    struct msgbuf rcvbuffer;

    key = 1234;

    if ((msqid = msgget(key, 0666)) < 0)
      die("msgget()");


     //Receive an answer of message type 1.
    if (msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0)
      die("msgrcv");

    printf("%s\n", rcvbuffer.mtext);
    exit(0);
}

如果您了解消息队列,那么消息队列用于进程间通信。

同样对于多个进程之间的双向通信你需要多个消息队列

关于c - C 中的消息队列 : implementing 2 way comm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22661614/

相关文章:

C - 将数组引用传递给函数中的指针参数时遇到问题

c++ - 在 C++ 中将函数指针中的 const 参数转换为非 const

C - pthread 函数重用 - 局部变量和竞争条件

linux - 执行相对于另一个用户的主目录的脚本

Linux 文件权限的正则表达式(数字符号)

c++ - 是否有任何可用的操作/围栏比发布弱但仍提供同步语义?

c - 指针和 libPcap

c - 是否可以使结构数组的地址等于指向 malloc 内存的指针?

计算C中二维数组中每一列的平均值?

c - 堆栈内存中的 free()