- 2
- 0
- 约4.15千字
- 约 6页
- 2019-11-11 发布于湖北
- 举报
《计算机操作系统》实验报告
实验题目 进程的管道通信实验
一、实验目的
1、了解什么是管道
2 、熟悉 UNIX/LINUX 支持的管道通信方式
3 、通过进程多次的循环读写学习利用管道进行进程间的通信
4 、验证 lockf 的加锁解锁作用
5 、验证读写进程本身是否已经实现了互斥作用
三、实验过程
编写程序实现进程的管道通信。用系统调用 pipe( ) 建立一管道,二个子进程 P1 和 P2 分别向
管道各写一句话:
Child P1 is sending a message!
Child P2 is sending a message!
父进程从管道中读出二个来自子进程的信息并显示(要求先接收 P1,后 P2)。
延迟 5 秒后显示
child 1 process is sending message!
再延迟 5 秒
child 2 process is sending message!
并实现循环 5 次读写
程序如下:
#include stdio.h
int pid1, pid2, i=0;
int main( )
{
int fd[2];
char OutPipe[100],InPipe[100];
pipe(fd);
while((pid1 = fork()) == -1);
if(pid1 == 0)
{
printf(\nChild1\n);
lockf(fd[1], 1, 0);
int i;
for(i=0;i5;i++)
{
sprintf(OutPipe, \n Child process %d is sending message!\n,i);
write(fd[1], OutPipe, 50);
sleep(5);
}
lockf(fd[1], 0, 0);
exit(0);
}
else
{
while((pid2 = fork()) == -1);
if(pid2 == 0)
{
printf(\nChild2\n);
lockf(fd[1], 1, 0);
int j;
for(j=0;j5;j++)
{
sprintf(OutPipe, \n Child process %d is sending message!\n,j);
write(fd[1], OutPipe, 50);
sleep(5);
}
lockf(fd[1], 0, 0);
exit(0);
}
else
{
printf(\nFather1\n);
int p;
for(p=0;p5;p++)
{
read(fd[0], InPipe, 50);
printf(%s\n, InPipe);
}
printf(\nFather2\n);
int q;
for(q=0;q5;q++)
{
read(fd[0], InPipe, 50);
printf(%s\n, InPipe);
}
exit(0);
}
原创力文档

文档评论(0)