pipe

#https://blog.csdn.net/ljianhui/article/details/10168031
#https://blog.csdn.net/yx_l128125/article/details/7680221
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<semaphore.h>
#include<fcntl.h>
sem_t *w,*r;
int main(){
	int filedis[2];
	pipe(filedis);
	char buf[256];
	char *name1="writer";
	char *name2="reader";
	int x,y;
	#https://baike.baidu.com/item/sem_open/8817672?fr=aladdin
	#https://www.cnblogs.com/Liu-Jing/p/7435699.html
	w=sem_open(name1,O_CREAT,0666,1);
	r=sem_open(name2,O_CREAT,0666,0);
	sem_getvalue(w,&x);
	#https://baike.baidu.com/item/sem_post/4281234?fr=aladdin
	if(x==0) sem_post(w);
	pid_t pid1,pid2,pid3;
	pid1=1;pid2=1;pid3=1;
	pid1=fork();
	#https://www.cnblogs.com/dongguolei/p/8086346.html
	if(pid1>0) pid2=fork();
	if(pid1>0&&pid2>0) pid3=fork();
	if(pid1==0){
		close(filedis[0]);
		sem_wait(w);
		printf("child process1 send message\n");
		write(filedis[1],"p1 ",strlen("p1 "));
		sem_post(w);
		sem_post(r);
		exit(0);
	}
	if(pid2==0){
		close(filedis[0]);
		sem_wait(w);
		printf("child process2 send message\n");
		write(filedis[1],"p2 ",strlen("p2 "));
		sem_post(w);
		sem_post(r);
		exit(0);
	}		
	if(pid3==0){
		close(filedis[0]);
		sem_wait(w);
		printf("child process2 send message\n");
		write(filedis[1],"p3 ",strlen("p3 "));
		sem_post(w);
		sem_post(r);
		exit(0);
	}
	if(pid1>0&&pid2>0&&pid3>0){
		sem_wait(r);
		sem_wait(r);
		sem_wait(r);
		sem_wait(w);
		printf("3 child process finish sending, the messages are:");
		close(filedis[1]);
		read(filedis[0],buf,sizeof(buf));
		printf("%s\n",buf);
		sem_post(w);
	}	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值