一、管道
管道通常是指无名管道,是UNIX系统IPC最古老的形式
特点:
它是半双工(即数据只能在一个方向上流动),具有固定的读端和写端。
它只能用于具有亲缘关系的进程之间的通信(也是父子进程或者兄弟进程之间)。
它可以看成是一种特殊的文件,对于它的读写也可以使用普通的read、write等函数。但是它不是普通的文件,并不属于任何文件系统,并且只存在于内存中。
原型:
#include <unistd.h>
int pipe(int pipefd[2]); // 返回值:成功返回0,失败返回-1
当一个管道建立时,就会创建两个文件描述符:fd[0]为读而打开,fd[1]为写而打开。
例子:(无名管道)
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
// int pipe(int pipefd[2]);
int main()
{
int fd[2];
int pid;
char buf[128];
if(pipe(fd) == -1){
printf("create pipe failed\n");
}
pid = fork();
if(pid < 0){
printf("create child failed\n");
}
else if(pid > 0){
sleep(3);
printf("this is father\n");
close(fd[0]);
write(fd[1], "hello from father", strlen("hello from father"));
wait();
}else{
printf("this is child\n");
close(fd[1]);
read(fd[0], buf, 128);
printf("read from father: %s\n",buf);
exit(0);
}
return 0;
}

无名管道有如下缺点:
不能使用open打开
只能父子进程间通信
半双工工作方式,读写端是分开的,fd[0]为读段,fd[1]写段
写入操作不具有原子性,只能用于一对一简单通信
不能用lseek来定位
注意:
管道有固定的读端和写端,管道为空,read()会阻塞,管道满时,write会阻塞。在操作管道是,要求读、写端都存在,写端关闭时,read直接返回,返回值为0。读端关闭时,write()会产生异常,收到SIGPIPE信号。