首页 > 学院 > 开发设计 > 正文

【linux】匿名管道pipe

2019-11-08 19:52:36
字体:
来源:转载
供稿:网友
管道是一种最基本的ipC机制,由pipe函数创建: #include <unistd.h>int pipe(int filedes[2]); 调用pipe函数时在内核中开辟一块缓冲区(称为管道)用于通信,它有一个读端一个写端,然后通过filedes参数传出给用户程序两个文件描述符,filedes[0]指向管道的读端,filedes[1]指向管道的写端(很好记,就像0是标准输⼊1是标准输出一样)。所以管道在用户程序看起来就像一个打开的文件,通过read(filedes[0]);或者write(filedes[1]);向这个文件读写数据其实是在读写内核缓冲

区。pipe函数调用成功返回0,调用失败返回-1。

1父进程调用pipe开辟管道,得到两个文件描述符指向管道的两端。2. 父进程调用fork创建⼦进程,那么子进程也有两个文件描述符指向同一管道。3. 父进程关闭管道读端,子进程关闭管道写端。父进程可以往管道里写,子进程可以从管道⾥读,管道是用环形队列实现的,数据从写端流入从读端流出,这样就实现了进程间通信。

例如

#include<stdio.h>#include<unistd.h>#include<errno.h>#include<string.h>#include<sys/wait.h>int main(){	int fds[2]={		-1,-1	};	if(pipe(fds)<0)	{		PRintf("pipe error.%s/n",strerror(errno));		return 2;	}	pid_t id=fork();	if(id==0)	{		close(fds[0]);        int count=5;		char* msg="hello world/n";		while(count--)		{			write(fds[1],msg,strlen(msg));			printf("write success. %d/n",count);		}		close(fds[1]);	}	else{		close(fds[1]);		int count=0;		char buf[1024];		while(count++<10){			ssize_t s=read(fds[0],buf,sizeof(buf)-1);			if(s>0)			{				buf[s]='/0';			}			printf("father msg from child:%s",buf);			if(waitpid(id,NULL,0)<0)			{			   return 3;			}		}	}	return 0;}结果


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表