消息队列的基本使用思路和接口介绍

本文档介绍了如何在C编程环境下使用消息队列。首先,通过`mk_id`函数生成消息队列的关键字,接着使用`msgget`创建消息队列。然后,展示了`Write_msg`函数用于写入消息,而`Recv_msg`函数则用于读取消息。在多进程环境中,两个进程并行读取消息队列,最后通过`Close_msg`函数删除消息队列。
摘要由CSDN通过智能技术生成
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>

#define MSGLENGTH 256
#define MSG 0010
/*
 *消息队列,在不关闭的情况下,只要拿到id就可以读取内容,但是当执行过msgrcv后
 * 该队列将被删除
 **/

/*生成key用于创建消息队列*/
key_t mk_id(int id)
{
    static char path[128 +1];
    static int flag=0;
    key_t key ;

    if( flag )
        goto _not_first_;

    sprintf(path,"%s/%s",getenv("HOME"),".bashrc");
    flag = 1 ;

_not_first_:
    key = ftok(path,id);
    return ( key );
}

/*销毁消息队列*/
int Close_msg(int id)
{
    return msgctl(id,IPC_RMID,0);
}

/*读取消息队列的内容*/
int Recv_msg(int id,int p_no)
{
    struct s_msg{
            long type;
            char mtext[256];
    } msg;
    int msg_len=0;
    while(1)
    {
        msg_len=msgrcv(id,&msg,MSGLENGTH,0,IPC_NOWAIT|MSG_NOER
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值