1、数据流只有一个方向,从“读端”到“写端”。
2、只有用于亲缘关系的进程间通信
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
intmain()
{
int fd[2];
int ret,bytes_write,bytes_read;
char *buf = "hello,pipe!";
char p[20];
ret = pipe(fd);
if( ret == -1 )
{
perror("pipe error");
exit(1);
}else{
bytes_write =write(fd[1],buf,strlen(buf));
if( -1 == bytes_write )
{
perror("write error");
exit(1);
}
bytes_read = read(fd[0],p,20);
if( -1 == bytes_read )
{
perror("read error");
exit(1);
}
p[bytes_read] = '\0';
printf("read pipe : %s\n",p);
exit(0);
}
}
3、半双工的通信模式,具有固定的读端和写端。
4、不允许交换管道的读写端。
5、关闭管道的写端,从读端读数据时read返回值为0,表示读管道到文件尾。
6、关闭管道的读端,往写端写数据时,此时出现管道破裂,内核会向当前进程发送SIGPIPE的信号,用户进程对于此信号的默认处理方式为终止当前进程。
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<signal.h>
intmain()
{
int fd[2];
char buf[100] = "hello,pipe!";
int bytes_read,bytes_write;
signal(SIGPIPE,SIG_IGN);
if( pipe(fd) < 0 )
{
perror("pipe error");
exit(1);
}else{
#if 0
close(fd[1]);
bytes_read = read(fd[0],buf,100);
if( -1 == bytes_read )
{
perror("read error");
exit(1);
}
printf("read pipe : %dbytes\n",bytes_read);
exit(0);
#else
printf("111111\n");
close(fd[0]);
printf("2222\n");
bytes_write =write(fd[1],buf,strlen(buf));
printf("3333333\n");
if( -1 == bytes_write )
{
perror("write error");
exit(1);
}
printf("bytes_write is%d\n",bytes_write);
exit(0);
#endif
}
7、TCP编程中,当通信的一端将套接字关闭,另外一端继续write,此时内核会向调用write的函数的进程发送SIGPIPE的信号,用户进程对于此信号的默认处理方式为终止当前进程。
8、不关闭读端,直接从读端读数据。
intmain()
{
int fd[2];
char buf[20];
int bytes_read;
if( pipe(fd) < 0 )
{
}else{perror("pipeerror");
exit(1);
printf("read before!\n");
bytes_read = read(fd[0],buf,20);
printf("read after!\n");
if( -1 == bytes_read )
{
perror("read error");
exit(1);
}
printf("bytes_read is %d\n",bytes_read);
exit(0);
}
}
9、多次写入,一次读取。如果读取的buff够大,会将管道中所有的数据读出。
intmain()
{
int fd[2];
char buf1[10] = "hello!";
char buf2[10] = "world!";
char buf[20];
int bytes_write,bytes_read;
if( pipe(fd) < 0 )
{
perror("pipe error");
exit(1);
}else{
bytes_write =write(fd[1],buf1,strlen(buf1));
if( -1 == bytes_write )
{
perror("write error");
exit(1);
}
bytes_write =write(fd[1],buf2,strlen(buf2));
if( -1 == bytes_write )
{
perror("write error");
exit(1);
}
bytes_read = read(fd[0],buf,20);
if( -1 == bytes_read )
{
perror("read error");
exit(1);
}
buf[bytes_read] = '\0';
printf("read pipe :%s\n",buf);
exit(0);
}
}
10、一次写入,多次读取。管道中第二次读数据时受阻塞。