工作需要,和大家共同学习总结。(学习的内容为传智播客linux服务器开发二、三部分)
1、管道,实际上是内核缓冲区;由两个文件文件描述符,一端读一端写;用于进程间通信
pipe,半双工的,用于有血缘关系的进程间通信
FIFO命名管道,用于非血缘关系的进程间交换数据
局限性:
数据自己读不能自己写
一旦数据被读走,便不在管道中,不可反复读
由于管道采用半双工的通信方式,因此只能在一个方向上流动
只能在有公共祖先的进程间使用管道
2、伪文件,不是真正的文件,不会占用磁盘空间
s 套接字 b块设备 c字符设备 p管道
3、 父子进程间利用管道通信
#include<unistd.h>
#include<cstdlib>
#include<iostream>
#include<sys/wait.h>
#include<fcntl.h>
#include<string>
using namespace std;
int main(int argc,char * argv[]){
int fd[2];
pid_t pid;
int ret=pipe(fd);
if(ret==-1){
perror("pipe error");
exit(1);
}
pid=fork();
if(pid==-1){
perror("fork error");
exit(1);
}else if(pid==0){
//子进程读
close(fd[1]);//关闭写端
char buf[1024];
int ret=read(fd[0],buf,sizeof(buf));
if(ret==0){
cout<<buf<<endl;
}
write(STDOUT_FILENO,buf,ret);
}else{
close(fd[0]);//关闭读端
string str="hello pipe\n";
write(fd[1],str.c_str() ,str.length());
}
return 0;
}