特點:
可以是非親緣進程之間;
讀寫必須同時進行,否則阻塞。
創建命名管道:
int mkfifo(pathname,mode);
參數:
pathname:
文件路徑(文件必須不存在)。
mode:
模式。
返回值:
0 成功
非0 失敗
創建FIFO管道代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(){
if(-1 == mkfifo("/tmp/test",0644)){//0表示8進制;6表示所有者可讀(4)寫(2);4表示同組成員可讀;4表示其他組成員可讀。
perror("mkfifo error");
return 1;
}
}
打開FIFO文件:
int open(const char* path, int mode);
參數:
path:
文件路徑。
返回值:
-1 失敗
其他 文件描述符
mode:
O_RDONLY 阻塞只讀
O_RDONLY|O_NONBLOCK 非阻塞只讀
O_WRONLY 阻塞只寫
O_WRONLY|O_NONBLOCK 非阻塞只寫
阻塞讀寫代碼:
阻塞只寫代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int main(){
int fd = open("/tmp/test",O_WRONLY);
if(-1 == fd){
perror("open error");
return 1;
}
char str[] = "Hello fifo";
write(fd,str,sizeof(str));
printf("write:%s\n",str);
}
阻塞只讀代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int main(){
int fd = open("/tmp/test",O_RDONLY);
if(-1 == fd){
perror("open error");
return 1;
}
char buf[BUFSIZ];
bzero(buf,BUFSIZ);
read(fd,buf,BUFSIZ);
printf("read:%s\n",buf);
}
注意:
fifowrite與fiforead要同時執行,纔會數據傳遞。否則會阻塞。
非阻塞讀寫代碼:
非阻塞讀:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int main(){
int fd = open("/tmp/test",O_RDONLY|O_NONBLOCK);
if(-1 == fd){
perror("open error");
return 1;
}
char buf[BUFSIZ];
bzero(buf,BUFSIZ);
read(fd,buf,BUFSIZ);
printf("read:%s\n",buf);
}
非阻塞寫:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int main(){
int fd = open("/tmp/test",O_WRONLY|O_NONBLOCK);
if(-1 == fd){
perror("open error");
return 1;
}
char str[] = "Hello fifo";
write(fd,str,sizeof(str));
printf("write:%s\n",str);
}
注意:
刪除命名管道代碼:
#include <unistd.h> int main(){ unlink("/tmp/test"); }