Linux操作系统-进程间通信—管道(父进程和两个子进程)
新乡学院计算机与信息工程学院
课程名称 操作系统原理 专 业 计算机科学与技术 班 级 3班 学 号 2013052701xx 姓 名 xxx
实验成绩 任课教师 xxx
2013年 12月 3日
实验名称 进程间通信—管道(父进程和两个子进程)
姓 名 xxx 成 绩
2013年 12月 10日 实验地点 A14-322 实验时间 一、 实验目的与要求
实验目的:进一步熟悉linux中创建进程的方法及其用途 实验要求:认真
二、 操作步骤
1、 编写pipe.c文件代码,代码如下:
#include
#include
#include
#include
int pid1, pid2;
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!");
/*把串放入数组outpipe中 */
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);
}
}
}
三、 实验结果
1:在终端输入gcc pipe.c -o pipe.out命令之后,运行pipe.out文件结果如下: [root@bogon 第十个]# indent -npro -kr -i8 -ts8 -sob -l280 -ss -ncs -cp1 pipe.c [root@bogon 第十个]# gcc pipe.c -o pipe.out
[root@bogon 第十个]# ./pipe.out
child 1 process is sending message!
child 2 process is sending message!
评语:
指导老师(签名):