现在的位置: 首页 > 综合 > 正文

操作系统实验2

2017年12月19日 ⁄ 综合 ⁄ 共 1013字 ⁄ 字号 评论关闭
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

抱歉!评论已关闭.