• 2025年8月19日 星期二

H30611-实验七-信号与管道通信

6 月 4, 2023

一、实验目的

1. 加深理解信号和管道的概念及实现进程间通信的原理。

2. 掌握信号通信机制,学会通过信号实现进程间的同步通信。

3. 掌握匿名管道通信机制,学会通过匿名管道实现进程间的数据通信。

二、实验内容

本实验实现父子进程之间的管道通信。程序中由父进程创建一个匿名管道,并创建了2个子进程。两个子进程都从管道写端(入口)写入一个发给父进程的消息(字符串),父进程则从管道读端(出口)读取发来的两个消息。

三、实验主要步骤

(1)程序设计

下面是程序的部分代码,请完成该程序的设计。

/*test7_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)多次运行test7_1,观察运行结果。

如果出现不符合要求的输出结果,问题出在什么地方?

修改程序,直到无错为止。

四、实验结果测试

1.修改所给代码,即进行创建一个匿名管道,分别向管道1,2写入消息并设置终止信号,待子进程终止后从管道先后读出两个消息,并输出相关提示信息。最后关闭管道。对于前30行的代码修改,如图1所示,对于31至44行的代码修改,如图2所示。

图1
图2

2.编译生成代码,结果如图3所示。

图3

六、附件下载

Avatar photo

李星海

简介: 2025-今 浙江农林大学 | 2022-今 广州白蓝碗蛋科技有限公司 | 2022-2024 广州商学院 | 2019-2022 广东工贸职业技术学院 | 服务宗旨:心始至客,行亦致远。