进程间通信 消息队列

1 消息的创建,发送和接受。
   使用系统调用 msgget( ), msgsnd(), msgrev() 及msgctl() 编制一长度为1K的消息发送和接受的程序。
   ! 为了便于操作和观察结果,用一个程序做为“引子”, 先后fork ()两个子进程, server  和 client , 进程通信。
   !! server 端建立一个Key 为  75 的消息队列 ,等待其他进程发来的消息,当遇到类型为1的消息,则作为结束消息, 取消该队列,并推出server. server每接收到一个消息后显示一个(server) received.
   !!!client 端使用Key 为75的消息队列,先后发送类型从10到1的消息,然后退出。最后的一个消息,既是server端的结束消息,client每发送一个消息后显示一句(client)sent.
#include<stdio.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<sys/ipc.h>


#define MSGKEY 175
struct msgform
{
    long mtype;
    char mtrex[1030];
}msg;
int msgqid , i;
void CLIENT()
{
    int i;
    msgqid = msgget(MSGKEY,0777);
    for(i = 10; i >= 1; i --)
    {
        msg.mtype = i ;
        printf("(client)sent/n");
        msgsnd(msgqid , & msg,1024,0);
    }
    exit(0);
}
void SERVER()
{
  msgqid = msgget(MSGKEY,0777|IPC_CREAT);
  do 
  {
      msgrcv(msgqid,&msg,1030,0,0);
      printf("(server)received/n");     
  }while(msg.mtype!=1);
  msgctl(msgqid,IPC_RMID,0);
  exit(0);
}
int  main()
{
  while((i= fork())==-1);
  if(!i)SERVER();
  while((i = fork())==-1);
  if(!i)CLIENT();
   wait(0);
   wait(0);
}


changtiger的电邮   o52tiger@yahoo.com.cn
--------------------- 
作者:changtiger 
来源:CSDN 
原文:https://blog.csdn.net/changtiger/article/details/1886577

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值