应用FIFO命名/命名管道(匿名)管道的一个限制是,只能在具有共同祖先(具有亲缘关系)的进程之间进行通信。

如果希望在不相关的进程之间交换数据,可以使用FIFO文件执行此操作。 这经常被称为命名管道。

命名管道是特殊类型的文件。

创建一个命名管道

1 )命名管道可以通过命令行创建:

$mkfifo filename

2 )命名管道在程序中创建。

# includesys/types.h # includesys/stat.hint mkfifo (const char * pathname,mode_t mode ); //例int main () if (mkfifo ),0644 )=-1 ) err _ exit (mkfifo error ); } FIFO与PIPE的区别:

1 )匿名管道由pipe函数创建和打开。

命名管道由mkfifo函数创建,并在open中打开

2 )命名管道(FIFO )和pipe )的唯一区别在于创建方法和打开方法不同,但在完成这些任务后, 它们是相同的含义(theonlydifferencebetweenpipesandfifosisthemannerinwhichtheyarecreatedandopened.oncethesetaskshavebeenacccccomplished

命名管道的打开规则

如果当前打开操作打开了FIFO进行读取

O_NONBLOCK disable :阻止此FIFOO_NONBLOCK enable进行写入:立即返回成功//示例1:块,使用只读int main () cout ‘ fifoo _ rdonlyopensuccess ‘ endl; //例2:只读,无阻塞且int main () intFD=open )、O_RDONLY|O_NONBLOCK ); if(FD==-1 ) err_exit(FIFOopenerror ); cout ‘ fifoo _ rdonlyopensuccess ‘ endl; }

如果当前打开操作打开了FIFO进行写入

O_NONBLOCK disable :阻止此FIFOO_NONBLOCK enable供相应进程读取:立即返回失败,错误代码由ENXIO//示例1:阻止并打开cout ‘ fifoo _ wronlyopensuccess ‘ endl; //例2:无阻塞,int main () intFD=open ),只需打开O_WRONLY|O_NONBLOCK )即可书写; if(FD==-1 ) err_exit(FIFOopenerror ); cout ‘ fifoo _ wronlyopensuccess ‘ endl; }

命名管道的读写规则同匿名管道

示例:不同进程之间使用命名管道的文件复制

写入管线进程:

# include stdio.h # include unistd.h # include stdlib.h # includesys/stat.h # includesys/types.h # include fcntl.hh exit(exit_failure; (} int infd; infd=open(argv[1],O_RDONLY ); //打开文件if (infd==-1 ) {perror ) ‘ openerror; exit(exit_failure; (if ) mkfifo )、tmpFifo (,0644 )=-1 ) (perror )、mkfifoerror ); exit(exit_failure; (} int fd; FD=open(‘tmpFIFO ‘,O_WRONLY ); //写入方式为if(FD==-1 ) {perror ) ‘ openerror; exit(exit_failure; } char buf[1024*4]; int n=0; while((n=read ) Infd,buf,1024*4) ) write ) FD,buf,n ); }关闭(infd ); 关闭(软盘); 打印成功(n ); 返回0; 读取过程:

# include stdio.h # include unistd.h # include stdlib.h # includesys/stat.h # includesys/types.h # include fcntl.hh exit(exit_failure; } int outfd; outFD=open(argv[1],O_WRONLY|O_CREAT|O_TRUNC ); //写入打开文件if (out FD==-1 ) perror ) ‘ openerror ); exit(exit_failure; (} int fd; FD=open(‘tmpFIFO ‘,O_RDONLY ); //以读取方式读取if(FD==-1 ) { perror } ‘ openerror ‘ ); exit(exit_failure; } char buf[1024*4]; int n=0; while((n=read ) FD,buf,1024*4) )//从管道读取数据write ) outFD,buf,n ); //写入文件}关闭(软盘); 关闭(out FD; 链接(tmp FIFO ); 读取成功(n ); 返回0; }