linux进程间通信:管道
一、什么是管道
在linux系统中,管道是将一个两个进程之间的标准输入与标准输出连接起来的机制,以半双工的方式工作(将一个进程的输出与另一个进程的输入连接起来的单向通信)。
对管道的读写与一般的I/O系统函数一致,但不支持某些特定的I/O操作,例如lseek()。
二、相关函数
函数原型 | int pipe(int pipefd[2]) |
---|---|
头文件 | <unistd.h> |
参数 | 描述 |
pipefd | 创建的管道文件描述符,pipefd[0]:读端;pipefd[1]:写端。 |
返回值 | 成功:0,失败:-1 |
函数原型 | int pipe2(int pipefd[2], int flags) |
---|---|
头文件 | <fcntl.h><unistd.h> |
参数 | 说明 |
pipefd | 创建的管道文件描述符 |
flags | 管道对应的属性标志 |
返回值 | 成功:0,失败:-1 |
flags:
0:同pipe();
O_NONBLOCK:设置创建的两个文件描述符的非阻塞属性;
O_CLOEXEC:close on exec.
三、其他
管道的数据量限制:PIPE_BUF,在limits.h中定义(不同的内核版本会有所不同)。
四、测试代码
#include<unistd.h>
#include<stdio.h>
#include<iostream>
int main()
{
int pipefd[2];
if(-1 == pipe(pipefd))
{
perror("Pipe create:");
return -1;
}
char read_buff[1024] = {0x00};
char write_buff[10240] = "Hello, Pipe.";
pid_t pid = fork();//创建线程分支
if(0 > pid)
{
perror("Process Create:");
return -1;
}
if(0 == pid)
{
close(pipefd[0]);//父进程关闭读端
int w_bytes = 10340;
while (0 < w_bytes)
{
int result = write(pipefd[1], write_buff, w_bytes);
if(0 < result)
{
w_bytes -= result;
}
}
}
else
{
close(pipefd[1]);//子进程关闭写端
while(true)
{
int nbytes = read(pipefd[0], read_buff, sizeof(read_buff));
if(0 >= nbytes)
{
std::cout << " No data left. " << std::endl;
break;
}
std::cout << "Recv amount: " << nbytes << " Recv data: " << read_buff << std::endl;
}
}
return 0;
}