IPC笔记总结(一)——无名管道

本文详细介绍了无名管道(Pipe)的读写规则,包括当读写端存在与否时的行为,并提供了两个示例:一个是自读自写的简单应用,另一个涉及创建两个线程分别进行读写操作。强调了在使用管道时,应当遵循先关闭读端再关闭写端的原则,以及无名管道主要用于亲缘进程间的单向通信。

目录

管道读写规则

无名管道(pipe)

无名管道举例

1.一个自读自写

2.创建两个线程,一个写入,一个读取;


管道读写规则

1.写入时候

(1)有读端存在时候,写端管道空间写入数据,管道满容量为65536(unsigned short 为65535),写管道阻塞;

(2)读端不存在时候,写端管道无意义,会发送SIGPIPE信号干掉管道进程。

2.读入时候

(1)有写端存在时候:

①管道中数据 >= 要求读取数据,读出要求数据;

②管道中数据 < 要求读取数据,读出管道中实际数据;

③管道无数据,阻塞;

(2)无写端存在时候:管道中有数据就读取数据,没有数据就返回0;

注意:使用管道时候,读端管道先关写端;写端管道先关读端;

无名管道(pipe)

1.父写子读,父进程关闭读取文字描述符,子进程关闭写入文件描述符;

2.多用于亲缘关系进程间的通信;

3.可用于任何同主机进程间的通信(单向);

4.使用pipe函数创建一个文件描述符数组——存取两个文件描述符,

int fd[2];
if (pipe(fd) < 0)
{
    perror("Fail to pipe");
    return -1;
}

无名管道代码例写

1.自读自写

#include <stdio.h>
#include <unistd.h>
#include <string.h>
//自读自写
int main(int argc, const char *argv[])
{
	int fd[2];
	int n;
	pid_t pid;
	char *str = "I love China";
	char buf[100]={0};

	if(pipe(fd)<0)
	{
		perror("Fail to pipe");
		return -1;
	}
	
	write(fd[1],str,strlen(str));

	n = read(fd[0],buf,sizeof(buf));

	printf("read %d bytes :%s\n",n,buf);

	close(fd[0]);
	close(fd[1]);

	return 0;
}

2.创建两个线程,一个写入,一个读取;

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/wait.h>
//父写子读

void write_f(int fd)
{
	char buf[1024] = {0};
	int n;
	while (1)
	{
		memset(buf,0,sizeof(buf));
		fgets(buf,sizeof(buf),stdin);
		write(fd,buf,strlen(buf));
		
        if(strncmp(buf,"quit",4) == 0)
		{
			break;
		}
	}
}

void read_f(int fd)
{
	char buf[1024] = {0};
	int n;
	while(1)
	{
		memset(buf,0,sizeof(buf));
		n = read(fd,buf,sizeof(buf));
		printf("读了 %d 个字符,字符串为: \n%s\n",n-1,buf);

		if(strncmp(buf,"quit",4) == 0)
		{
			break;
		}
	}
}

int main(int argc, const char *argv[])
{
	int fd[2];
	int n;
	pid_t pid;
	char *str = "I love China";
	char buf[100]={0};

	if(pipe(fd)<0)
	{
		perror("Fail to pipe");
		return -1;
	}
	
	write(fd[1],str,strlen(str));
	n = read(fd[0],buf,sizeof(buf));
	
	pid = fork();
	
	if (pid < 0)
	{
		perror("Fail to fork");
		return -1;
	}
	else if (pid > 0)
	{
		close(fd[0]);
		write_f(fd[1]);
		wait(NULL);//Don't lose: recycle the chile
	}
	else if (pid == 0)
	{
		close(fd[1]);
		read_f(fd[0]);

	}
	close(fd[0]);
	close(fd[1]);

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yh_lhn_20

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

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

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

打赏作者

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

抵扣说明:

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

余额充值