当前位置:文档之家› 城院操作系统 实验报告_实验八

城院操作系统 实验报告_实验八

浙江大学城市学院实验报告
课程名称操作系统原理实验
实验项目名称实验八进程通信——管道
学生姓名专业班级学号
实验成绩指导老师(签名)日期
注意:
●务请保存好各自的源代码,已备后用。

●请上传到BB平台。

一. 实验目的和要求
1.了解Linux系统的进程间通信机构(IPC);
2.理解Linux关于管道的概念;
3.掌握Linux支持管道的系统调用和管道的使用;
4.巩固进程同步概念。

二、实验内容
用系统调用pipe( )创建管道,实现父子进程间的通信。

三、实验步骤
1、并发进程的无管道通信
1)编译运行给出的pipe1.c,观察运行结果。

执行前:
执行:
执行后:
2)思考:观察程序运行结果,比较新旧文件的内容是否有差异,并分析原因。

有。

程序将f1中的内容按字符逐个读出,并逐个写入到了f2中。

2、多进程的管道通信,编译并运行给出的代码pipe3.c,观察并理解多进程通过管道通信。

3、编写程序:(来自第三章习题)假定系统有三个并发进程read,move和print共享缓冲器B1和B2。

进程read负责从输入设备上读信息,每读出一个记录后把它存放到缓冲器B1中。

进程move从缓冲器B1中取出一个记录,加工后存入缓冲器B2。

进程print将B2中的记录取出打印输出。

缓冲器B1和B2每次只能存放一个记录。

要求三个进程协调完成任务,使打印出来的与读入的记录的个数,次序完全一样。

试创建三个进程,用pipe( )打开两个管道,如错误!未找到引用源。

所示,实现三个进程之间的同步。

程序源码:
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <semaphore.h>
#include <fcntl.h>
int pid1,pid2;
/*sem_t *S1;
sem_t *S2;
sem_t *S3;
sem_t *S4;*/
//sem_t S1;
//sem_t S2;
//sem_t S3;
//sem_t S4;
int valp;
main( )
{
/* S1=sem_open("A",O_CREAT,0644,1);
S2=sem_open("B",O_CREA T,0644,0);
S3=sem_open("C",O_CREA T,0644,0);
S4=sem_open("D",O_CREAT,0644,1);*/
// sem_init(&S1,0,1);
// sem_init(&S2,0,0);
// sem_init(&S3,0,0);
// sem_init(&S4,0,1);
int fd1[2];
int fd2[2];
char pipe1[100],pipe2[100],pipe3[100];
pipe(fd1); /*创建一个管道*/
pipe(fd2);
while ((pid1=fork( )) == -1);
if(pid1 == 0)
{
while ((pid2=fork( )) == -1);
if(pid2==0)
{
while(1)
{
// S1=sem_open("A",O_EXCL);
// sem_wait(S1);
lockf(fd1[1],1,0);
/*把输出串放入数组outpipe中*/
printf("process1 is sending message to pipe1\n");
sprintf(pipe1,"%d",rand());
write(fd1[1],pipe1,50); /*向管道写长为50字节的串*/
lockf(fd1[1],0,0);
// printf("1111111111\n");
// S2=sem_open("B",O_EXCL);
// sem_post(S2);
// printf("22222222222\n");
}
}
else
{
while(1)
{
//sem_open(const char *name,int oflag,mode_t mode,unsigned int value);
// printf("33333333333\n");
// S2=sem_open("B",O_EXCL);
// sem_wait(S2);
// printf("44444444444\n");
// S4=sem_open("D",O_EXCL);
// sem_wait(S4);
printf("process2 is reading message from pipe1\n");
read(fd1[0],pipe2,50);
printf("process2 had received the message:%s\n",pipe2);
lockf(fd2[1],1,0);
printf("process2 is sending message to pipe2\n");
write(fd2[1],pipe2,50);
lockf(fd2[1],0,0);
// S1=sem_open("A",O_EXCL);
// sem_post(S1);
// S3=sem_open("C",O_EXCL);
// sem_post(S3);
}
}
}
else
{
while(1)
{
// S3=sem_open("C",O_EXCL);
// sem_wait(S3);
printf("process3 is reading message from pipe2\n");
read(fd2[0],pipe3,50);
printf("process3 had received the message:%s\n",pipe3);
// S4=sem_open("D",O_EXCL);
// sem_post(S4);
}
}
}
程序运行结果:
程序分析:
程序实现了read,move和print的模拟。

进程1将一个随机数传进pipe1,进程2从pipe1接收数据并将数据传送进pipe2,程序3从pipe2读出数据。

这个程序同步上存在问题(同步的操作已注释)。

刚开始我用的是无名信号灯,后来发现无名信号灯只能在一个进程内的不同线程之间使用,不同进程之间共享不了信号量。

于是改用有名信号灯,改用有名信号灯后遇到了问题,使用sem_post()对有名信号灯操作时,信号量增加不了。

四、讨论、心得
记录实验感受、上机过程中遇到的困难及解决办法、遗留的问题、意见和建议等。

相关主题