管道
分类:命名管道和匿名管道
- 命名管道:可以用于本机上的任意进程间通信
- 匿名管道:只适用于拥有亲缘关系的进程间通信
本质:是内核中开辟的一块缓冲区
特性:
- 读写特性:当一个进程读或者写时,其他进程不能读或者写
- 自带同步与互斥
- 半双工通信:数据只能向一段发送数据,若要双方通信,则要使用两个管道
- 提供字节流服务
- 生命周期随进程
匿名管道
原型
int pipe(int fd[2]);
fd:文件描述符数组,其中fd[0]表示读端,fd[1]表示写端
成功返回0,失败返回错误代码
//从键盘读取数据,写入管道,读取管道,写到屏幕
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main( void )
{
int fds[2];
char buf[100];
int len;
if ( pipe(fds) == -1 )
perror("make pipe"),exit(1);
// read from stdin
w