#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);
}
}
pipe
最新推荐文章于 2024-05-22 15:12:37 发布