单向通道示例

//管道是父进程和子进程间单向的通信机制,即一个进程发送数据到管道,另一个进程从管道中读取数据。如果需要双向的通信机制则需要建立两个管道
//系统负责两件事情:一是写入管道的数据和读出管道的数据的顺序是相同的。
// 二是数据不会再管道中丢失,除非这个管道过早地退出。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

void read_data(int pipes[])
{
	int c;
	int rc;
	//关闭写的一端
	close(pipes[1]);
	
	//读数据并打印
	while((rc=read(pipes[0],&c,1))>0){
	    putchar(c);
	}
	exit(0);
}

//父进程写数据
void write_data(int pipes[])
{
	int c;
	int rc;
	//关闭读的一端
	close(pipes[0]);
	//从控制台读数据并向管道写数据
	while((c=getchar())>0){
		rc=write(pipes[1],&c,1);
        if(rc==-1){
			perror("Parent:write");
			close(pipes[1]);
			exit(1);
		}	
	}
	
	//关闭写一遍
	close(pipes[1]);
	exit(0);
}

int main(int argc,char *argv[])
{
	int pipes[2];
	pid_t pid;   //fork返回的进程号
	int rc;
	
	//建立管道
	rc=pipes(pipes);
	if(rc==-1){
		perror("pipe");
		exit(1);
	}
	
	//建立子进程
	pid=fork();
	switch(pid){
		//失败
		case -1:
			perror("fork");
			exit(1);
		//子进程
		case 0:
			read_data(pipes);
			//不能到这里
		//父进程
		default:
			write_data(pipes);
			//不能到这里/
	}
	
	return 0;
}

转载于:https://my.oschina.net/liubin/blog/23816

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值