Linux操作系统实验系列之实验四管道通信
一、实验目的1、了解什么是管道2、熟悉UNIX/LINUX支持的管道通信方式二、实验内容:编写程序实现进程的管道通信。用系统调用pipe( )建立一管道,二个子进程P1和P2分别向管道各写一句话:Child 1 is sending a message!Child 2 is sending a message!父进程从管道中读出二个来自子进程的信息并显示。三、实验环境Linux操作系统四、实验过程
一、实验目的
1、了解什么是管道
2、熟悉UNIX/LINUX支持的管道通信方式
二、实验内容:
编写程序实现进程的管道通信。用系统调用pipe( )建立一管道,二个子进程P1和P2分别向管道各写一句话:
Child 1 is sending a message!
Child 2 is sending a message!
父进程从管道中读出二个来自子进程的信息并显示。
三、实验环境
Linux操作系统
四、实验过程与运行结果
源代码:
#include<unistd.h>
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
int pid1,pid2;
int main()
{
int fd[2];
char outpipe[100],inpipe[100];
pipe(fd);/create a pipe/
while((pid1=fork())-1);
if(pid10)
{
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(pid20)
{
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);
}
}
}
结果图:
更多推荐