进程间通信——无名管道

 管道

int main()
{
	int pipefd[2];   // 0 读端   1 写端
	int ret = pipe(pipefd);
	
	if (-1 == ret)
	{
		perror("创建管道失败\n");
		
		return -1;
	}
	
	write(pipefd[1], "hello", 6);
	
	while (1)
	{
		char buf[10] = {0};
		
		//1、管道中的数据是一次性的,读完就没有了
		//2、当管道中没有数据的时候,read 将会阻塞,直到管道中有数据才返回
		read(pipefd[0], buf, 10);
		
		printf ("buf = %s\n", buf);
	} 
	
	close(pipefd[0]);
	close(pipefd[1]);
	
	return 0;
}

父子间进程通信

#include <stdio.h>
// 包含pipe、fork
#include <unistd.h>

#include <string.h>

#define SIZE 1024

// 子进程工作: 往管道写数据
// void child_do(int pipefd[2])
void child_do(int *pipefd)
{
	// 关闭读端
	close(pipefd[0]);
	
	char buf[SIZE] = {0};
	
	while(1)
	{
		fgets(buf, SIZE, stdin);
		write(pipefd[1], buf, strlen(buf));
	}
	
	// 关闭写端
	close(pipefd[1]);
}

// 父进程工作:从管道读数据
void father_do(int pipefd[2])
{
	// 关闭写端
	close(pipefd[1]);
	
	char buf[SIZE+1];
	
	while(1)
	{
		// ssize_t read(int fd, void *buf, size_t count);
		ssize_t ret = read(pipefd[0], buf, SIZE);
		
		if (-1 == ret)
		{
			perror("读文件失败");
		}
		
		buf[ret+1] = '\0';
		
		printf ("父进程读到的数据:%s", buf);	
	}
	
	// 关闭读端
	close(pipefd[0]);
}

// 不同进程间的通信本质:进程之间可以看到一份公共资源;
// 而提供这份资源的形式或者提供者不同,造成了通信方式不同,
// 而 pipe就是提供这份公共资源的形式的一种。

// (1)父进程创建管道,得到两个文件描述符指向管道的两端
// (2)父进程fork出子进程,子进程也有两个文件描述符指向同一管道。
// (3)父进程关闭fd[0],子进程关闭fd[1],即父进程关闭管道读端,子进程关闭管道写端(因为管道只支持单向通信)。
// 父进程可以往管道里写,子进程可以从管道里读,管道是用环形队列实现的,
// 数据从写端流入,从读端流出,这样就实现了进程间通信。 
int main()
{
	// int pipe(int pipefd[2]);
	// 0 读端 1 写端
	// 1、创建管道
	int pipefd[2];
	int ret = pipe(pipefd);
	
	// 2、创建子进程
	// pid_t fork(void);
	pid_t pid = fork();
	
	switch(pid)
	{
		case -1:
			// 创建失败
			perror("创建子进程失败");
			break;
		case 0:
			// 子进程
			child_do(pipefd);
			break;
		default:
			// 父进程
			father_do(pipefd);
			break;
	}
	
	printf ("\n");
	
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值