一、有名管道
特点:
1、创建之后会在文件系统以管道文件的形式存在
2、可以在任意两个进程间通信,没有固定的读写端
代码:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
// 创建管道,在文件系统生成fifo管道文件
int ret=mkfifo("fifo",0664);//0664赋文件权限
//0664--> rw- rw- -w-,每一位依次对应<用户>、<用户组><其他>的权限,每个权限又对应读(r)写(w)执行(x)
if(ret<0)
{
printf("mkfifo fail\r\n");//ret<0,就输出创建错误原因
return(-1);
}
/* 写入fifo */
#if 1
int fd=open("fifo",O_WRONLY);//以‘仅写’打开管道
if(fd<0)
{
printf("open fifo fail\r\n");
return(-1);
}
char send_buf[256]={0};//定义缓冲区大小
while(1)
{
fgets(send_buf,sizeof(send_buf),stdin);//获取输入的字符串
write(fd,send_buf,strlen(send_buf));//写入
}
close(fd);
#endif
/* 读取fifo */
#if 0
int fd=open("fifo",O_RDONLY);//以‘仅读’打开管道
if(fd<0)
{
printf("open fifo");
return(-1);
}
char recv_buf[64]={0};
while(1)
{
read(fd,recv_buf,sizeof(recv_buf));//读取缓冲区
printf("recv msg:%s\r\n", recv_buf);//输出
}
close(fd);
#endif
return 0;
}
二、无名管道
特点:
1、创建之后在文件系统不可见
2、半双工通信
3、固定的读端(0),写端(1)
4、只能用于具有亲缘关系的进程间的通信
代码:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
int pipe_fd[2]; // pipe_fd[0] 为读端 pipe_fd[1] 为写端
int ret = pipe(pipe_fd);
if(ret < 0)
{
printf("fail to pipe\n");
return -1;
}
pid_t pid = fork();
if(pid > 0)
{
close(pipe_fd[0]); // 关闭读端
while(1)
{
char buff[1024] = "send msg: hello world\r\n";
write(pipe_fd[1], buff, strlen(buff)+1);
}
wait(NULL);
close(pipe_fd[1]);
}
else if(0 == pid)
{
close(pipe_fd[1]); // 关闭写端
while(1)
{
char buff[1024] = {0};
read(pipe_fd[0], buff, sizeof(buff));
printf("recv msg:%s", buff);
}
close(pipe_fd[0]);
}
else
{
printf("fail to fork\n");
return -1;
}
return 0;
}
有名和无名之间区别:
1、无名只能在有亲缘关系的进程通信
2、有名也称命名管道,可以在任意两个进程间通信