【实验目的】
一、1、了解什么是管道
2、熟悉 UNIX/LINUX 支持的管道通信方式
实验要求:了解熟悉LINUX支持的管道机制
【实验内容】
1、编制一段程序,实现进程的管道通信。使用pipe()建立一条管道线。两个子进程p1和p2分别向管道各写一句话:
Child 1 is sending message!
Child 2 is sending message!
而父进程则从管道中读出来自于两个子进程的信息,显示在屏幕上。
2.在父进程中用pipe()建立一条管道线,往管道里写一句话,两个子进程接收这句话。
【实验环境】(含主要设计设备、器材、软件等)
Pc电脑一台,虚拟机中LINUX环境
【实验步骤、过程】(含原理图、流程图、关键代码,或实验过程中的记录、数据等)
1.创建一个管道,通过pipe(fd)函数得到两个文件描述符,fd[0]用于读取,fd[1]用于写入。使用fork()函数创建两个子进程,分别为pid1和pid2。
在第一个子进程(pid1)中,使用lockf函数进行文件锁定,然后通过write将一个消息写入管道,表示"child 1 process is sending message!"。之后,通过sleep(5)模拟进程的一些处理时间,最后释放文件锁并退出。
在第二个子进程(pid2)中,同样使用lockf进行文件锁定,然后通过write将另一条消息写入管道,表示"child 2 process is sending message!"。同样,通过sleep(5)模拟处理时间,最后释放文件锁并退出。
在父进程中,使用wait(0)等待子进程的结束。然后通过read从管道中读取子进程写入的消息,并打印输出。这里通过两次循环,分别读取两个子进程的消息。
流程图:
#include<stdio.h>
#include<unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int pid1,pid2;
int main()
{
int fd[2];
char OutPipe[100],InPipe[100];
pipe(fd);
while((pid1=fork())== -1);
if(pid1==0)
{
lockf(fd[1],1,0);
sprintf(OutPipe,"child 1 process is sending message!");
write(fd[1],OutPipe,50);
sleep(5);
lockf(fd[1],0,0);
exit(0);
}
else
{
while((pid2=fork())== -1);
if(pid2==0)
{
lockf(fd[1],1,0);
sprintf(OutPipe,"child 2 process is sending message!");
write(fd[1],OutPipe,50);
sleep(5);
lockf(fd[1],0,0);
exit(0);
}
else
{
wait(0);
read(fd[0],InPipe,50);
printf("%s\n",InPipe);
wait(0);
read(fd[0],InPipe,50);
printf("%s\n",InPipe);
exit(0);
}
}
}
2.创建一个管道。使用fork()函数创建两个子进程,分别为pid1和pid2。
在第一个子进程(pid1)中,通过read从管道中读取消息,然后打印输出。
在第二个子进程(pid2)中,同样通过read从管道中读取消息,然后打印输出。
在父进程中,通过write向管道中写入两次消息,表示"Parent is sending message!"。然后使用wait(0)等待两个子进程的结束。
流程图:
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
int pid1,pid2;
int main()
{
int fd[2];
char OutPipe[100],InPipe[100];
pipe(fd);
while((pid1 = fork()) == -1);
if(pid1 == 0)
{
read(fd[0],InPipe,50);
printf("#pid1 %s\n",InPipe);
exit(0);
}
else
{
while((pid2 = fork()) == -1);
if(pid2 == 0)
{
read(fd[0],InPipe,50);
printf("#pid2 %s\n",InPipe);
exit(0);
}
else
{
sprintf(OutPipe,"Parent is sending message!");
write(fd[1],OutPipe,50);
sprintf(OutPipe,"Parent is sending message!");
write(fd[1],OutPipe,50);
wait(0);
wait(0);
exit(0);
}
}
return 0;
}
【实验结果或总结】(对实验结果进行相应分析,或总结实验的心得体会,并提出实验的改进意见)
1.从输出来看,"child 1 process is sending message!"和"child 2 process is sending message!"这两条消息已经成功地由子进程发送并被父进程接收和打印出来。说明程序已经成功地实现了进程间的通信。
2.从输出来看,”Parent is sending message!”这条消息已经成功地由父进程发送并被两个子进程接收和打印出来。程序运行多次,进程pid1和pid2谁先读管道内容具有随机性。