Linux_消息队列

概念
消息队列是消息的链接表,存储在内核中,由消息队列标识符标识。

#include<sys/msg.h>
int msgget(key_t key, int flag);
    //创建或打开消息队列,若成功返回消息队列ID,失败返回-1

int msgctl(int msqid, int cmd, struct msqid_ds *buf);
    //cmd参数指定执行命令,IPC_RMID可以删除消息队列

int msgsnd(int msqid, const void *ptr, size_t nbytes, int flag);
    //把消息放入消息队列

int msgrcv(int msqid, void *ptr, size_t nbytes, long type, int flag);
    //从消息队列中取数据

实例
写入:


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

struct mymesg
{
    long mtype;    //通道号
    char buf[100];  //存放消息内容
};

int main()
{
    struct mymesg m;
    int msqid = msgget(1234, IPC_CREAT|0644);
    if(msqid < 0)
        perror("msgget"),exit(1);
    while(1)
    {
        memset(m.buf, 0x00,sizeof(m.buf));
        printf("mtype:");
        scanf("%d", &m.mtype);  //输入通道号
        printf("text:");
        scanf("%s", m.buf);    //输入内容
        msgsnd(msqid, &m, sizeof(m.buf), 0);   //把内容放入相应通道号的消息队列
    }
    return 0;
}

取出:


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

struct mymesg
{
    long mtype;
    char buf[100];
};

int main()
{
    struct mymesg m;
    int msqid = msgget(1234, 0);
    if(msqid < 0)
        perror("msget"),exit(1);
    while(1)
    {
        memset(m.buf, 0x00,sizeof(m.buf));
        printf("mtype:");
        scanf("%d", &m.mtype);    //输入通道号
        msgrcv(msqid, &m, sizeof(m.buf), m.mtype, 0);  //把内容保存在m.buf
        printf("text:%s\n", m.buf);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/cute_shuai/article/details/80383743