进程的通信管理-进程的管道通信

 

编制一段程序,实现进程的管道通信。使用系统调用pipe()建立一条管道线。两个子进程p1和p2分别向管道各写一句话:

而父进程则从管道中读出来自两个子进程的信息,显示在屏幕上。

#include<stdio.h>
#include<unistd.h>//添加fork()函数头文件
#include<signal.h>//signal头文件
#include<stdlib.h>//exit需头文件

int main(){
	int fd[3],pid1,pid2;
	char OutPipe[100],InPipe[100];
	pipe(fd);//创建管道,fd[0]指向管道的读端,fd[1]指向管道的写端
	while((pid1=fork())==-1);
	if(pid1==0){
		printf("p1\n");
		lockf(fd[1],1,0);
		sprintf(OutPipe,"child1 is sending a message!");//给OutPipe赋值
		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,"child2 is sending a message!");
			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);
			printf("%s\n",InPipe);
			wait(0);
			read(fd[0],InPipe,50);
			printf("%s\n",InPipe);
			exit(0);
		}
	}
	return 0;
}

运行截图:

  • 18
    点赞
  • 94
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值