FIFO(有名管道)與Pipe(無名管道)都是通過內核緩衝區來進行通信,Pipe(無名管道)只能用於有緣進程之間的通信,而FIFO(有名管道)亦可 用於無緣進程之間的通信。創建一個FIFO(有名管道),其也擁有像文件名那樣的名稱,可以通過 ls -l 命令查看,文件類型爲p。
FIFO寫端:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define MX_SIZE 1024
int main()
{
int fd=-1;
int n=-1;
char buf[MX_SIZE]="hello";
mkfifo("./FIFO",0664); //創建FIFO FIFO的權限 = 0664&~umasK(0022)
fd = open("./FIFO",O_WRONLY); //只寫
if(fd < 0)printf("open error\n");
n = write(fd,buf,MX_SIZE);
if(n < 0)printf("write error\n");
return 0;
}
寫端以只寫(O_WRONLY)的方式打開FIFO,調用write函數時,會阻塞到讀端打開爲止。如果以讀寫的方式打開(O_RDWR),就不會阻塞。
FIFO讀端:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define MAX_SIZE 1024
int main()
{
int fd;
char *buf;
int n;
fd = open("./FIFO",O_RDONLY);
if(fd < 0)printf("open error\n");
n = read(fd,buf,MAX_SIZE);
if(n < 0)printf("write error\n");
printf("buf=%s\n",buf);
return 0;
}
通信結果:
要以非阻塞的方式來打開FIFO,須在open函數中指定O_NONBLOCK參數。