Linux进程间通信之无名管道通信
1、无名管道是什么?
用于父子进程通信的一种方式,实质,在内核空间中的一段缓冲区,和stdin、stdout、stderr 一样,并且这个缓冲区是65536字节。管道,和真正的水管一样,一端在父进程,一端在子进程,管道两端的其中一端有两个端口,一个是读端、一个是写端,只不过,在使用过程中,父进程的读端关闭,子进程的写端关闭。
2、无名管道的规则
①有读端,写管道空闲,则写入数据,管道满则阻塞;
②读端不存在,写管道无意义,内核发送SIGPIP信号,杀死写管道进程;
③读取过程中,读取要求大小的数据,若管道内的数据不够,则有多少读多少,没有则读管道阻塞;
④写端不存在,管道有数据,则读数,没数据不阻塞,立即返回0;
3、如何创建
#include"stdio.h"
#include"unistd.h"
int main(int argc, const char argv[])
{
int fd[2];
if(pipe(fd)<0)
{
perror("Fail to pipe");
return -1;
}
printf("f[0]=%d\n",f[0]);
printf("f[0]=%d\n",f[1]);
}
4、小试牛刀:
#include"stdio.h"
#include"unistd.h"
#include"string.h"
void write_file(int fd)
{
char buf[1024];
int n;
while(1)
{
memset(buf,0,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
n=write(fd,buf,strlen(buf));
if(strncmp(buf,"quit",4)==0)
{
break;
}
}
}
void read_file(int fd)
{
char buf[1024]={0};
int n=0;
while(1)
{
memset(buf,0,sizeof(buf));
n=read(fd,buf,sizeof(buf));
if(n<0)
{
perror("Fail to read");
return ;
}
printf("Read:%ld bytes:%s\n",strlen(buf),buf);
if(strncmp(buf,"quit",4)==0)
{
break;
}
}
}
int main(int argc, const char *argv[])
{
int fd[2];
pid_t pid;
if(pipe(fd)<0)
{
perror("Fail to pipe");
return -1;
}
pid=fork();
if(pid<0)
{
perror("Fail to fork");
return -1;
}
else if(pid==0)
{
close(fd[1]);
read_file(fd[0]);
}
else if(pid>0)
{
close(fd[0]);
write_file(fd[1]);
}
return 0;
}