[導讀]匿名管道呢,只能使用在有親緣關系的進程之間,比如父子進程個兄弟進程,等等,因為匿名管道是一個在內存中存在的文件,其地址描述符只是在父子進程之中才有體現,為了克服該缺點,就有了命名管道的實現,命名管道呢
匿名管道呢,只能使用在有親緣關系的進程之間,比如父子進程個兄弟進程,等等,因為匿名管道是一個在內存中存在的文件,其地址描述符只是在父子進程之中才有體現,為了克服該缺點,就有了命名管道的實現,命名管道呢,實際上就是一個在文件系統(tǒng)中存儲的文件,命名管道是一個設備文件,同時,該管道文件也是FIFO(First? In First Out)的形式,即,第一個被寫入的數據,將第一個被讀出
創(chuàng)建命名管道的系統(tǒng)函數
int? mkfifo(const char* path,mode_t mode);path指示的是管道文件的全路經,mode則是管道模式和具有存取權限
int? mknod(const char* path,mode_t mode,dev_t dev)同上,但是dev為設備值,取決于文件的創(chuàng)建類型。
現在說下他的編碼實現,因為管道操作是半雙工通信,有名管道呢,其主要含義就是根據管道到文件所在的路徑進行通信的,也就是說,我們要進行相應的東西,進行操作
現在看下server
/* ?*?main.cpp ?* ?*??Created?on:?Jul?16,?2014 ?*??????Author:?john ?*/ #include#include#include#include#include#include#include#include#includeusing?namespace?std; //#define?FIFO_READ?"/tmp/writefifo" #define?FIFO_WRITE?"/tmp/readfifo" #define?BUF_SIZE?1024 int?main() { ???int?wfd; ????char?ubuf[BUF_SIZE]={0}; ???umask(0); ???if(mkfifo(FIFO_WRITE,S_IFIFO|0666)) ???{ ??????cout<<"sorry?the?namedpipe?created?error"<<strerror(errno)<<endl; ??????exit(0); ???} ???umask(0); ??wfd=open(FIFO_WRITE,O_WRONLY); ??if(wfd==-1) ??{ ????cout<<"open?named?pipe?error"<<FIFO_WRITE<<strerror(errno)<<endl; ????exit(1); ??} ??cout<<"begin...n"; ??int?nCount=0; ??while(1) ??{ ??cout<<"please?input?the?content:"<>ubuf; ??if(strcmp(ubuf,"exit")==0) ??{ ??exit(0); ??} ?int?leng=?write(wfd,ubuf,strlen(ubuf)); ?if(leng>0) ?{ ?cout<<"write..."<<nCount<<endl; ?nCount++; ?} ??} }
現在看下client操作
/* ?*?main.cpp ?* ?*??Created?on:?Jul?16,?2014 ?*??????Author:?john ?*/ #include#include#include#include#include#include#include#include#includeusing?namespace?std; #define?FIFO_READ?"/tmp/readfifo" #define?BUF_SIZE?1024 int?main() { ???int?rfd; ???char?ubuf[BUF_SIZE]={0}; ???umask(0); ???while((rfd=open(FIFO_READ,O_RDONLY))==-1) ???{ ??cout<<"open..."<<strerror(errno)<<endl; ?????sleep(1); ???} ??cout<0) ?????{ ???????ubuf[len]='