Linux C 学习日记(3)消息队列

使用消息队列 ,使两个程序可以互相发送信息。

                                          程序一:
#include<sys/msg.h>
#include<string.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
int main()
{
  key_t key;
  struct msgbuf{
        long mtype;   //消息类型
        char buff[1024]; //消息长度
  }buf;             //定义一个消息队列
 int id,pid;
 key=ftok("/",'s');
 id=msgget(key,IPC_CREAT|0777);   //创建消息队列
 pid=fork();
 if(pid>0)
 {
 while(1)
  {
   buf.mtype=2;     //表示消息的类型 接收时,接收对应的消息类型  类型是 2
   fgets(buf.buff,1024,stdin);  //从屏幕读取数据
   msgsnd(id,(void *)&buf,strlen(buf.buff)+1,0);  //发送数据 “+1” 包括了回车键 
  }
  wait();
 }
else (pid==0);
{
while(1)
 {
  msgrcv(id,&buf,sizeof(buf.buff),3,0);  //接收消息类型为 3 的信息
  printf("%s",buf.buff);
 }
}
return 0;
}

           第二个程序与第一个程序大体类似,需注意 **发送和接收是一对**
                                 它们的消息类型是一样的   
                                      程序二:                           
#include<sys/msg.h>
#include<string.h>
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/types.h>
int main()
{
 key_t key;
 struct msgbuf{
        long mtype;
        char buff[1024];
        }buf;
 int id,pid;
 key=ftok("/",'s');
 id=msgget(key,IPC_CREAT|0777);
 pid=fork();
 if(pid==0)
{
while(1)
 {
  msgrcv(id,&buf,sizeof(buf.buff),2,0);   //接收消息 类型是 2 和第一个发送的消息是一样的
  printf("%s",buf.buff);
 }
}
else(pid>0);
{
while(1)
  {
  buf.mtype=3;      //发送消息  类型是 3
  fgets(buf.buff,1024,stdin);
  msgsnd(id,(void *)&buf,strlen(buf.buff)+1,0);
  }
wait();
}
return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值