[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
操作系统——实验三(进程间通信)——3.3.4
实验目的
1、了解linux系统中进程通信的基本原理。
2、分析进程竞争资源现象,学习解决进程互斥的方法。
3.3.4进程的管道通信(必做)
编制一段程序,实现进程的管道通信。使用系统调用pipe()建立一条管道先。两个子进程p1和分别向管道各写一句话:
Child1processissendingamessage!
Child2processissendingamessage!
而父进程则从管道中读出来自于两个子进程的信息并显示在屏幕上。
第一步
创建c文件夹,在它下面创建hello.c文件
mkdir c vim test.c
第二步
写入参考程序
程序
#include<unistd.h> #include<stdio.h> #include<signal.h> int pid1,pid2; main()
{ int fd[3]; char outpipe[100],inpipe[100]; pipe(fd); while((pid1=fork())==-1);
if(pid1==0) { printf("p1\n"); lockf(fd[1],1,0);
sprintf(outpipe,"child1processissendingamessage!"); write(fd[1],outpipe,50);
sleep(1); lockf(fd[1],0,0); exit(0); } else { while((pid2=fork())==-1);
if(pid2==0) { printf("p2\n"); lockf(fd[1],1,0);
sprintf(outpipe,"child2processissendingamessage!"); write(fd[1],outpipe,50);
sleep(1); lockf(fd[1],0,0); exit(0); } else { printf("parent\n");
wait(0);/*同步*/ read(fd[0],inpipe,50);/*从管道中读长为50字节的串*/ printf("%s\n",inpipe);
wait(0); read(fd[0],inpipe,50); printf("%s\n",inpipe); exit(0); } } }
结果
相关知识
无名管道( pipe ):管道是一种半双工的通信方式,数据只能单向流动,而且只能在具有亲缘关系的进程间使用。进程的亲缘关系通常是指父子进程关系。
有名管道(namedpipe):有名管道也是半双工的通信方式,但是它允许无亲缘关系进程间的通信。
管道通信的特点:管道只能承载无格式字节流。
观察程序中的sleep(1)起什么作用?
答:延长子进程占用管道的时间,并没有让子进程1先输出而子进程2后输出的作用。
子进程1和2为什么也能对管道进行操作?
答:因为该pipe管道属于无名管道,调用pipe()的父进程及其子孙进程均能识别此文件描述符,能利用该文件(管道)进行通信。
(摘自实验报告书)