消息队列(一)

消息队列与pipe类似,但是存在两个区别:

1. message boundaries are preserved, so that readers and writes communicate in units of messages, rather than via an undelimited byte stream.

2.each message includes an integer type field, and it's possible to select messages by type.

相关的数据结构:

1.msqid_ds 消息队列数据结构: 用于标示整个消息队列的基本情况

2.msg 消息队列数据结构:整个消息队列的主体

</pre><pre name="code" class="cpp">#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

int main(int argc, char *argv[])
{
    key_t key;
    int msgid;
    struct msqid_ds buf;
    //生成key,IPC在实现是约定使用key值作为参数创建,param1:文件路径名,param2:一个int变量
    if( (key = ftok(".", 'A')) == -1 )
    {
        perror("ftok");
        exit(EXIT_FAILURE);
    }
    //创建消息队列,param1:key值,param2:权限
    if((msgid = msgget(key, 0666|IPC_CREAT)) == -1 )
    {
        perror("msgget");
        exit(EXIT_FAILURE);
    }

    /*

    *消息队列属性控制

    * extern int msgctl(int __msqid, int __cmd, struct msqid_ds *__buf);
       __cmd:
              #define IPC_RMID 0 // remove resource     这种删除是立即生效的,只有相应的权限才能操作
              #define IPC_SET 1 // set ipc_perm options 
              //设置消息队列的属性,按照buf指向的结构体中的值:msg_perm.uid\msg_perm.gid\msg_perm\mode\msg_qbytes
              //有效用户ID 等于msg_perm.cuid/msg_perm.uid或root才能执行
             #define IPC_STAT 2 // get ipc_perm options 取得此队列的msqid_ds结构,并存在buf指向的结构体中
             #define IPC_INfO 3 // see ipcs
      */
    msgctl(msgid, IPC_STAT, &buf);
    printf("the key: %d,\nthe uid:%d,\nthe gid:%d,\nthe cuid:%d,\nthe cgid:%d,\nthe mode:%o,\n\
the squence:%d\n",buf.msg_perm.__key, buf.msg_perm.uid,
            buf.msg_perm.gid, buf.msg_perm.cuid, buf.msg_perm.cgid,
            buf.msg_perm.mode, buf.msg_perm.__seq);
    printf("the max bytes is: %lu\n", buf.msg_qbytes);
    //删除消息队列
    msgctl(msgid, IPC_RMID, (struct msqid_ds *)0);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值