命名管道
和匿名管道一样,命名管道也是在内核中开辟的一段缓存区,不过和匿名管道不同的是,这段缓存区是有标识符的,这也就意味着不同的进程,不需要有亲缘关系,只需要通过标识符就能找到该缓冲区了。
命名管道的创建
命令创建
命名管道可以从命令行上创建,命令行创建是使用下面这个命令:
mkfifo filename
"p"代表文件类型为管道文件
注意:该文件是不支持直接写的,该文件的作用是通过它我们可以找到内核中的创建的缓冲区
函数创建
相关函数:
mkfifo函数:
函数原型:
#include <sys/stat.h>
int mkfifo(const char *filename,, mode_t mode);
返回值:成功返回0,失败返回-1
代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
int main()
{
int fifoid = mkfifo("./fifoTest",0664);
if(fifoid < 0)
{
perror("mkfifo");
return -1;
}
return 0;
}
运行结果:
一个完整的例子:
这个例子在namePipe.c中先向缓冲区中写入了hello linux!然后再read.c中读出所写的内容。
namePipe.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
int main()
{
int fifoid = mkfifo("./fifoTest",0664);
if(fifoid < 0)
{
perror("mkfifo");
return -1;
}
printf("创建成功!\n");
int fd = open("./fifoTest",O_RDWR | O_CREAT);
if(fd < 0)
{
perror("open");
return -1;
}
else
{
ssize_t w_size = write(fd,"hello linux!",12);
if(w_size < 0)
{
perror("write");
return -1;
}
printf("write:%d",w_size);
}
while(1)
{
printf("wait!\n");
sleep(1);
}
return 0;
}
read.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int fd = open("./fifoTest",O_RDONLY);
if(fd < 0)
{
perror("open");
return -1;
}
else
{
char *buf[1024] = {0};
int ret = read(fd,buf,12);
if(ret < 0)
{
perror("read");
return -1;
}
printf("buf is : %s\n",buf);
}
return 0;
}
namePipe.c的运行结果:
另一个终端中read.c的运行结果:
特性
(1) 生命周期跟随进程
(2) 命名管道具有表示符
(3) 其它特性和匿名管道一样