杭电操作系统实验三之实现一个管道通信程序

2)实现一个管道通信程序

       由父进程创建一个管道,然后再创建三个子进程,并由这三个子进程利用管道与父进程之间进行通信:子进程发送消息,父进程等待三个子进程全部发完消息后再接收信息。通信的具体内容可根据自己的需要随意设计,要求能试验阻塞型读写过程中的各种情况,测试管道的默认大小,并且要求利用Posix信号量机制实现进程间对管道的互斥访问。运行程序,观察各种情况下,进程实际读写的字节数以及进程阻塞唤醒的情况。

#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;
	w=sem_open(name1,O_CREAT,0666,1);
	r=sem_open(name2,O_CREAT,0666,0);
	sem_getvalue(w,&x);
	if(x==0) sem_post(w);
	pid_t pid1,pid2,pid3;
	pid1=1;pid2=1;pid3=1;
	pid1=fork();
	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);
	}	
}

猜你喜欢

转载自blog.csdn.net/qq_42276781/article/details/98523996