管道pipe()使用说明
pipe()是unix/linux中的系统调用用于构建管道。
管道即在命令行中表现为command1 | command2的对象。
基本用法
- 使用pipe()需要引入头文件<unistd.h>
-pipe()基本格式为 pipe(int pipegate[2])
数组pipegate中存储两个文件描述符,分别用于向管道写入信息和从管道读取信息 。
-两个元素pipegate[0]和pipegate[1]像是管道的入口和出口,所以我把它命名为pipegate(意为管道的大门)
所以我们在程序中创建管道可以用下面的方法:
int pipegate[2];//声明pipegate
pipe(pipegate);//向pipegate写入文件描述符
管道的读写
- 管道读写使用read和write,一般和读写文件无异
形如:
const buffersize = 4096;
char buffer[buffersize];
//从管道中读取最多4096字节数据
read(pipegate[0],buffer,buffersize)
//向管道写入最多4096字节数据
write(pipegate[1],buffer,buffersize);