IPC通信之共享队列

//msgrcv 为阻塞函数

/*A process create msg and send msg*/

#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>
#include<sys/types.h>
struct msgbuf
{
  long type;
  char data[100];
}
main()
{
//1.create messge queue
  key_t key=ftok(".",254);
  int msgid=msgget(key,IPC_CREAT|IPC_EXCL|0666);
//2.contruct data
  int i;
  for(i=0;i<10;i++)
  {
    struct msgbuf msg={};
    msg.type=1;
    sprintf(msg.data,"%s:%d","message",i);
//3.send message
    msgsnd(msgid,&msg,sizeof(msg.data),0);
  }
  for(i=0;i<10;i++)
  {
     struct msgbuf msg={};
     msg.type=2;
     sprintf(msg.data,"%s:%d","messagetype2",i);
     msgsnd(msgid,&msg,sizeof(msg.data),0);
  }
//4.delete queue
 // msgctl(msgid,IPC_RMID,0);
}

===================================================

/*B process open msg queue and read msg*/

#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>
struct msgbuf
{
  long type;
  char data[100];
}
main()
{
//1.open messge queue
  key_t key=ftok(".",254);
  int msgid=msgget(key,0);
//2.receive message
  while(1)
  {
    struct msgbuf buf={};
    msgrcv(msgid,&buf,sizeof(buf.data),2,0);
    printf(":%s\n",buf.data);
    sleep(1);
  }
//3.delete queue
  msgctl(msgid,IPC_RMID,0);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值