命名管道的基本概念
- 命名管道与前篇文章中的半双工管道非常相似
- 在文件系统中命名管道是以设备特殊文件的形式存在的
- 不同的进程可以通过命名管道共享数据,与普通管道不同的是可与无血缘关系的进程进行通信。
声明
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo (consta char* pathname , mode_t mode);
例子
写端:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <cstring>
#include <iostream>
using namespace std;
int main(int argc , char **argv){
int wfd = open("mypipe",O_WDONLY);
if( wfd < 0 ){
printf( "open failed " );
return -1;
}
int ret = mkfifo ("mypipe" , 0664);
if( ret < 0){
printf ( "mkfifo failed" );
return -1;
}
while(1){
char buf[1024];
cin >> buf;
ret = write(wfd , buf ,sizeof (buf));
if(ret >= 0 ){
printf( " buf: %s",buf );
}
}
close (wfd);
return 0;
}
读端:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <cstring>
int main(int argc , char **argv){
int rfd = open("mypipe",O_RDONLY);
if( rfd < 0 ){
printf( "open failed " );
return -1;
}
int ret = mkfifo ("mypipe" , 0664);
if( ret < 0){
printf ( "mkfifo failed" );
return -1;
}
char buf[1024];
while(1){
ret = read(rfd , buf ,sizeof (buf));
if(ret >= 0 ){
buf[ret]= 0x00;
printf( " buf: %s",buf );
}
else
{
break;
}
}
close (wfd);
return 0;
}