匿名管道的操作
只能在具有亲缘关系的进进程之间进行通信。
int pipe(int pipefd[2])
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
int main()
{
int pipefd[2] = {
-1};
int ret = pipe(pipefd);
if(ret < 0)
{
perror("pipe error");
return -1;
}
pid_t pid = fork();
if(pid == 0)
{
char buf[1024];
read(pipefd[0],buf,1023);
}
else if(pid > 0)
{
char *str = "hello";
write(pipefd[1],biff,str);
}
return 0;
}
命名管道的操作:
支持同一个主机中的不同进行之间进行访问。
int mkfifo(char* name, mode_t mode)
//管道名称与权限。
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/stat.h> //命名管道
#include<errno.h> //错误处理
#include<fcntl.h> //文件操作
int main()
{
umask(0); //设置权限信息
//mkfifo(命名管道名称,管道操作权限)
int ret = mkfifo("./test_fifo",664);
if(ret < 0 && error != EEXIST) //创建失败或者已经存在
{
perror("mkfifo error");
return -1;
}
int fd = open("./test.fifo",O_RDONLY); //以只读的方式打开文件
if(fd < 0)
{
perror("open fifo error");
return -1;
}
return 0;
}
注意
文件以只读的方式打开,则会被阻塞,直到文件用写的方式进行打开。
文件以只写的方式打开,则会被阻塞,直到文件用读的方式打开。
管道的读写特性:
- 管道是半双工通信,可选择方向进行数据传输。
- 如果管道中没有数据则read会阻塞,如果管道中的数据已经写满了,则write会阻塞。
- 如果管道的写端出现异常,则读端读完管道中的数据后,返回0不在阻塞。
- 如果管道的读端被关闭,则写段报错。
- 管道的生命周期随进程,当操作管道的所有进程都被退出,则管道被释放。
- 管道提供字节流传输服务,不会读取相同的数据。
- 管道自带同步与互斥。
管道自带同步与互斥
同步: 通过条件判断实现对临界资源访问的时序合理性。体现在管道中为管道的读写特性
互斥: 通过唯一访问实现对临界资源访问的安全性。管道的读写操作在PIPE_BUF中保证了原子性。