前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Linux进程间通信之消息队列

Linux进程间通信之消息队列

作者头像
xcywt
发布2018-01-11 17:26:46
2.8K0
发布2018-01-11 17:26:46
举报
文章被收录于专栏:xcywtxcywt

  马上过年了,心里万般滋味。。。

一,消息队列

1,概念:“消息队列”是在消息的传输过程中保存消息的容器

2,消息队列就是一个消息的链表。可以把消息看作一个记录,具有特定的格式以及特定的优先级。

  对消息队列有写权限的进程可以向消息队列中按照一定的规则添加新消息

  对消息队列有读权限的进程则可以从消息队列中读走消息

  消息队列是随内核持续的。

3,编程注意事项:使用时先把数据封装成消息,把消息存入队列

编程步骤: 具体函数的用法可以用man手册查看(强力推荐)

(1)ftok()生产key

(2)使用msgget( ) 创建/获取消息队列,返回值是队列标识符

(3)使用msgsnd( ) 发送消息

    使用msgrcv( ) 接收消息

(4)使用msgctl( ) 删除消息队列

4,实例:

sendmsg.c   用来发送消息的

代码语言:javascript
复制
// sendmsg.c

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

struct my_msg
{
    int mtype; // 消息类型
    char buf[256];
}msg1, msg2;

int main()
{
    key_t key = ftok("./", 88);

    int msgid = msgget(key, 0666|IPC_CREAT);
    if(-1 == msgid)
    {
        perror("msgget failed!!!");
        exit(1);
    }

    msg1.mtype = 2;
    strcpy(msg1.buf, "hello, msg2");
    msgsnd(msgid, &msg1, sizeof(msg1), 0); // 阻塞
//    msgsnd(msgid, &msg1, sizeof(msg1), IPC_NOWAIT); // 非阻塞

    msg2.mtype = 1;
    strcpy(msg2.buf, "hello, msg1");
    msgsnd(msgid, &msg2, sizeof(msg2), 0); // 阻塞

    printf("消息发送完成,按回车销毁消息队列\n");
    getchar();

    if(-1 == shmctl(msgid, IPC_RMID, NULL))
    {
        perror("shmctl failed");
        exit(2);
    }
    return 0;
}

recvmsg.c  用来接收消息的

代码语言:javascript
复制
// recvmsg.c

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

struct my_msg
{
    int mtype; // 消息类型
    char buf[256];
}msg;

int main()
{
    key_t key = ftok("./", 88);

    // 获取消息队列
    int msgid = msgget(key, 0);
    if(-1 == msgid)
    {
        perror("msgget failed!!!");
        exit(1);
    }

    int res = msgrcv(msgid, &msg, sizeof(msg),
            2, // 取消息类型为2的消息
            0);
    printf("类型:%d, 内容:%s\n", msg.mtype, msg.buf);

    printf("消息接收完成,按回车销毁消息队列\n");
    getchar();

    if(-1 == shmctl(msgid, IPC_RMID, NULL))
    {
        perror("shmctl failed");
        exit(2);
    }
    return 0;
}

5,运行结果

6,获取代码  

git clone https://github.com/xcywt/xcyipc.git

有人看到这个麻烦再乌班图中试试这个库有没有建好。主要是学习github的一些用法。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-01-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档