操作系统-父子进程管道通信-编程实现

编写一个程序使用系统调用fork生成3个子进程,并使用系统调用pipe创建一个管道,使得这3个子进程和父进程公用同一管道进行信息通信。

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <strings.h>
main(){
	int i, r, p1, p2, p3, fd[20];
	char buf[50], s[50];
	pipe(fd);		//父进程建立管道
	while((p1 = fork()) == -1);		//创建子进程P1,失败时循环
	if(p1 == 0){		//由子进程P1返回,执行子进程P1 
		lockf(fd[1], 1, 0);			//加锁锁定写入端		
		sprintf(buf, "child process P1 is sending messages!\n");
		printf ("child process P1!\n");
		write(fd[1], buf, 50);		//把buf中的50个字符写入管道 
		sleep(5);		//睡眠5秒,让父进程读 
		lockf (fd[1], 0, 0);		//释放管道写入端 
		exit(0);     //关闭 
	}else{		//从父进程返回,执行父进程 
		while((p2 = fork()) == -1);
		if(p2 == 0){
			lockf(fd[1], 1, 0);
			sprintf(buf, "child process P2 is sending messages!\n");
			printf ("child process P2!\n");
			write(fd[1], buf, 50);
			sleep(5);
			lockf (fd[1], 0, 0);
			exit(0);
		}else{
			while((p3 = fork()) == -1);
			if(p3 == 0){
				lockf(fd[1], 1, 0);
				sprintf(buf, "child process P3 is sending messages!\n");
				printf ("child process P3!\n");
				write(fd[1], buf, 50);
				sleep(5);
				lockf (fd[1], 0, 0);
				exit(0);
			}
			wait(0);
			if((r = read(fd[0], s, 50)) == -1){
				printf ("can`t read pipe!\n");
			}else{
				printf ("%s\n", s);
			}
			wait(0);
			if((r = read(fd[0], s, 50)) == -1){
				printf ("can`t read pipe!\n");
			}else{
				printf ("%s\n", s);
			}
			wait(0);
			if((r = read(fd[0], s, 50)) == -1){
				printf ("can`t read pipe!\n");
			}else{
				printf ("%s\n", s);
			}
			exit(0);				
		}
	}	 
}

结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员Ale-阿乐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值