广 广 州 商 学 院 操作系统实验报告(第七次)
实验名称:
实验七、信号与管道通信 一.
实验目的 1. 加深理解信号和管道的概念及实现进程间通信的原理。
2. 掌握信号通信机制,学会通过信号实现进程间的同步通信。
3. 掌握匿名管道通信机制,学会通过匿名管道实现进程间的数据通信。
二.
实验内容 本实验实现父子进程之间的管道通信。程序中由父进程创建一个匿名管道,并创建了 2 个子进程。两个子进程都从管道写端(入口)写入一个发给父进程的消息(字符串),父进程则从管道读端(出口)读取发来的两个消息。
三.
实验主要步骤
(1)程序设计 下面是程序的部分代码,请完成该程序的设计。
/*test5_1.c:匿名管道*/ # include <stdio.h> # include <unistd.h> int main( ) {
int i ,p1 ,p2 , pid , fd[2] ;
char buf[80];
<创建一个匿名管道>
while((p1=fork( ))==-1);
if (p1==0) {
/*子进程 1 代码*/
sprintf (buf,”Message of child_1”); /*在 buf 中写入消息文本*/
<向管道写入消息>
printf (“Child_1 write an message to pipe!\n”);
for( i=0; i<99999; i++);
<终止> }
else{
while((p2=fork())==-1);
if (p2==0){
/*子进程 2 代码*/
sprintf (buf,”Message of child_2”);
<向管道写入消息>
printf (“Child_2 write an message to pipe!\n”);
for( i=0; i<99999; i++);
<终止>
}
else {
/*父进程代码*/
<等待子进程终止>
<从管道中先后读出两个消息,并输出相关提示信息>
<关闭管道>
printf(“OVER\n”);
}
} return 0; }
要求程序输出结果如下所示:
Child_1 write an message to pipe! Child_2 write an message to pipe! Parent read an message of child_1: Message of child_1 Parent read an message of child_2: Message of child_2 OVER 其中,前两行的顺序可颠倒,第 3 和第 4 行的顺序也可颠倒。
或:
Child_1 write an message to pipe! Parent read an message of child_1: Message of child_1 Child_2 write an message to pipe! Parent read an message of child_2: Message of child_2 OVER 或:
Child_2 write an message to pipe! Parent read an message of child_2: Message of child_2 Child_1 write an message to pipe! Parent read an message of child_1: Message of child_1 OVER (2)编辑、编译、调试该程序。
(3)多次运行 test5_1,观察运行结果。
如果出现不符合要求的输出结果,问题出在什么地方? 修改程序,直到无错为止。
四.
实验结果测试 (粘贴程序源代码及截图运行结果。)
分析与思考
五.
心得体会与自我评价 通过本次实验,我加深理解了信号和管道的概念及实现进程间通信的原理,基本掌握了
信号通信机制,学会通过信号实现进程间的同步通信,也掌握了匿名管道通信机制,学会如何通过匿名管道实现进程间的数据通信。
六.
教师评分