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;
}

猜你喜欢

转载自blog.csdn.net/Black_goat/article/details/83962318