Loading

操作系统实验四

1. 实验目的及要求

学习如何利用管道机制、消息缓冲队列、共享存储区机制进行进程间的通信,并加深对上述通信机制的理解。

2. 实验内容

1.了解系统调用pipe()的功能和实现过程。
2.编写一C语言程序,使其用管道来实现父子进程间通信。子进程向父进程发送字符串“is sending a message to parent!”;父进程则从管道中读出子进程发来的消息,并将其显示到屏幕上,然后终止。
3.运行该程序,观察、记录并简单分析其运行结果。

3. 实验源码

\#include<stdio.h>

\#include<unistd.h>

\#include<stdlib.h>

\#include<sys/types.h>

\#include<sys/ipc.h>

\#include<string.h>

\#include<sys/msg.h>

\#include<math.h>

 

\#define MSGKEY 75

 

struct msgbuf{

   long mtype;

   char mtext[1024];

};

 

int main()

{

   int pid;

   int msqid;

 

   struct msgbuf sendermsgp,recevermsgp;

   

 

   msqid=msgget((key_t)MSGKEY,IPC_CREAT|0666);

   if(msqid<0){

​     printf("wrong in function of msget\n");

​     return 0;

   }

 

 

   if((pid=fork())<0){

 

​     printf("There have something wrong in the function of fork");

​     return 0;

 

   }else if(pid==0){

​     printf("This is child process!\n");

​     sendermsgp.mtype=1;

​     char *sendmessage="serving for client";

​     sprintf(sendermsgp.mtext,"%s %d","serving for client",getpid());

 

 

​     msgsnd(msqid,&sendermsgp,strlen(sendermsgp.mtext)+1,0);

​    

​     printf("child send message:%s\n",sendermsgp.mtext);

​     

 

​     

​     printf("child process get sleep for watting the message gived by parent\n");

​     sleep(3);

​     sendermsgp.mtype=1;

​     msgsnd(msqid,&sendermsgp,strlen(sendermsgp.mtext)+1,0);

​     sprintf(sendermsgp.mtext,"%d",getpid());

​     printf("this is child second time send to parent context:%s\n",sendermsgp.mtext);

​      

 

 

​     int number;      

​     number=msgrcv(msqid,&recevermsgp,1024,0,0);

​     printf("-----child received message:%s\n",recevermsgp.mtext);

​     printf("end of child process\n");

​     

   }else{

​     printf("This is parent process:%d\n",getpid());

 

​     sleep(3);

​     printf("--------------------------------\n");

​     msgrcv(msqid,&recevermsgp,1024,0,0);

​     printf("parent get child message::%s\n",recevermsgp.mtext);

​     

​     

 

​     

​     

​     recevermsgp.mtype=pid;

​     sprintf(recevermsgp.mtext,"%d",getpid());

​     printf("##################%s\n",recevermsgp.mtext);

​     msgsnd(msqid,&recevermsgp,strlen(recevermsgp.mtext)+1,0);

​     printf("end of parent process\n");

​     sleep(2);

​    

   } 

   return 0;

}

4. 实验结果

结果分析

消息缓冲机制。当写进程把一定数量的数据写入pipe,便去睡眠等待,直到读进程取走数据后,再把它唤醒。当读进程读一空的pipe时,也应睡眠等待,直到写进程将数据写入管道后,才将之唤醒,从而实现进程的同步。

posted @ 2020-12-25 23:12  桥木  阅读(287)  评论(0)    收藏  举报