Operation of anonymous pipes
Communication can only be carried out between related processes.
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;
}
Operation of named pipes:
Supports access between different processes in the same host.
int mkfifo(char* name, mode_t mode)
//Pipe name and permissions.
#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;
}
note
文件以只读的方式打开,则会被阻塞,直到文件用写的方式进行打开。
文件以只写的方式打开,则会被阻塞,直到文件用读的方式打开。
Read and write characteristics of the pipeline:
- The pipeline is half-duplex communication, and the direction can be selected for data transmission.
- If there is no data in the pipeline, read will block, and if the data in the pipeline is full, write will block.
- If an exception occurs on the write end of the pipeline, the read end will return 0 after reading the data in the pipeline and it is not blocked.
- If the read end of the pipe is closed, an error is reported for the write segment.
- The life cycle of the pipeline varies with the process. When all processes operating the pipeline are exited, the pipeline is released.
- The pipe provides byte stream transmission service and does not read the same data.
- The pipeline comes with synchronization and mutual exclusion.
The pipeline comes with synchronization and mutual exclusion
Synchronization: Realize the timing rationality of access to critical resources through conditional judgment. Reflected in the pipeline, the read and write characteristics of the pipeline are
mutually exclusive: the security of access to critical resources is achieved through unique access. Pipeline read and write operations are guaranteed atomicity in PIPE_BUF.