特点
有名管道
在磁盘上有这样一个文件 ls -l -> p
伪文件,在磁盘大小永远为0
在内核中有一个对应的缓冲区
半双工的通信方式
使用场景
没有血缘关系的进程间通信
创建方式
命令:mkfifo 管道名
函数:mkfifo
fifo文件可以使用IO函数进行操作
open/close
read/write
不能执行lseek操作
使用fifo进行无血缘关系的进程间通信
1、 创建一个fifo文件 — fifo
2、 两个不相干的进程 A(a.c) B(b.c)
a.c —> read
§ int fd = open(“fifo”, O_RDONLY);
§ read(fd, buf, sizeof(buf));
§ close(fd);
b.c ----- write
int fd1 = open(“fifo”, O_WRONLY);
write(fd1, “hello, world”, 11);
close(fd1);
测试源码
write_fifo.c测试源码
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
int main(int argc, const char* argv[])
{
if(argc < 2)
{
printf("./a.out fifoname\n");
exit(1);
}
// 判断文件是否存在
int ret = access(argv[1], F_OK);
if(ret == -1)
{
int r = mkfifo(argv[1], 0664);
if(r == -1)
{
perror("mkfifo error");
exit(1);
}
printf("有名管道%s创建成功\n", argv[1]);
}
int fd = open(argv[1], O_WRONLY);
if(fd == -1)
{
perror("open error");
exit(1);
}
char *p = "hello, world";
while(1)
{
sleep(1);
int len = write(fd, p, strlen(p)+1);
}
close(fd);
return 0;
read_fifo.c测试源码
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
int main(int argc, const char* argv[])
{
if(argc < 2)
{
printf("./a.out fifoname\n");
exit(1);
}
// 判断文件是否存在
int ret = access(argv[1], F_OK);
if(ret == -1)
{
int r = mkfifo(argv[1], 0664);
if(r == -1)
{
perror("mkfifo error");
exit(1);
}
printf("有名管道%s创建成功\n", argv[1]);
}
int fd = open(argv[1], O_RDONLY);
if(fd == -1)
{
perror("open error");
exit(1);
}
char buf[512];
while(1)
{
int len = read(fd, buf, sizeof(buf));
buf[len] = 0;
printf("buf = %s, len = %d\n", buf, len);
}
close(fd);
return 0;
}
测试结果
写端
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char const *argv[])
{
int ret, fd;
ret = mkfifo("./myfifo",0777);
if(ret < 0)
{
if(errno != EEXIST)
{
perror("mkfifo");
return ret;
}
}
fd = open("./myfifo", O_RDWR);
write(fd,"hello world", 11);
while(1);
return 0;
}
读端
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char const *argv[])
{
int ret, fd;
char buf[128] = { 0 };
ret = mkfifo("./myfifo", 0777);
if(ret < 0)
{
if(errno != EEXIST)
{
perror("mkfifo");
return ret;
}
}
fd = open("./myfifo", O_RDWR);
if(fd < 0)
{
perror("open");
}
printf("-----------------\n");
read(fd, buf, 11);
printf("buf:%s\n",buf);
while(1);
return 0;
}