有名管道即文件系统中存在这个一样文件节点,每一个文件节点都有一个inode号。而且其是一个特殊的文件类型:p管道类型
创建这个有名管道,不可以通过open 函数,open 函数只能创建普通文件,不能创建特殊文件。
函数mkfifo()
mkfifo 用来创建管道文件的节点,没有在内核中创建管道。只有通过open 函数打开这个文件时才会在内核空间创建管道。
函数形式:int mkfifo(const char * filename,mode_t mode);
功能:创建管道文件
参数:管道文件文件名(要包含所在的路径),权限,创建的文件权限和umask有关系。
返回值:创建成功返回0,创建失败返回-1。
mkfifo的用法:创建有名管道
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
int main()
{
int ret;
ret = mkfifo("./myfifo",0777);
if(ret < 0){
printf("create fifo failure.\n");
}
printf("create fifo success.\n");
return 0;
}
执行结果:
CLC@Embed_Learn:~/linux_io/02/02/four$ ls
a.out myfifo myfifo.c
CLC@Embed_Learn:~/linux_io/02/02/four$ ls -l
total 16
-rwxr-xr-x 1 CLC book 8430 Nov 14 22:28 a.out
prwxr-xr-x 1 CLC book 0 Nov 14 22:28 myfifo//p为管道文件
-rw-r--r-- 1 CLC book 222 Nov 14 22:28 myfifo.c
通过管道实现无亲缘关系进程间通信。
第一个进程
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int i;
int fd;
int process_inter = 1;
fd = open("./myfifo",O_WRONLY);
if(fd < 0){
printf("open myfifo failure.\n");
return -1;
}
printf("open myfifo success.\n");
for(i=0;i<5;i++){
printf("This is frist main %d\n",i);
}
sleep(5);
write(fd,&process_inter,1);
// sleep(5);
while(1);
return 0;
}
第二个进程
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int i;
int fd;
int process_inter = 0;
fd = open("./myfifo",O_RDONLY);
if(fd < 0){
printf("open myfifo failure.\n");
return -1;
}
read(fd,&process_inter,1);
while(process_inter == 0);
for(i=0;i<5;i++){
printf("This is second main %d\n",i);
}
while(1);
return 0;
}
执行结果:第一个程序与第二个程序没有任何关系,通过有名管道进行通信。
现象:执行第一个程序的时候,因为没有读出,所以不会打印,只有运行第二个程序,才会开始打印。先打印完第一个程序的内容,再打印第二个。
无名管道和有名管道的区别:有名管道有生成文件,无名管道没有生成文件。