FIFO
雖然有名管道在親緣進程間非常方便,但由於它沒有名字所以使用範圍非常有限。FIFO不同於有名管道之處在於它提供一個路徑名與之關聯,以FIFO文件的形式存在於文件系統中。這樣只要其它進程可以訪問該路徑,就能與創建FIFO的進程通過FIFO進行通信。
FIFO嚴格遵循先進先出,對管道及FIFO的讀總是從開始處返回數據,對它們寫則在末尾添加數據。它們不支持諸如lseek()等文件定位操作。
程序演示:
兩個程序運行有先後順序,先運行fifor.c編譯後的程序
程序功能是通過FIFO實現文件的拷貝
#include
#include
#include
#include
#include
#include
#define SIZE 1024 //緩衝區大小
#define FIFO_SERVER "../FIFO" //FIFO文件路徑
//錯誤退出函數
void err_exit(char* msg)
{
printf("%s\n",msg);
exit(EXIT_FAILURE);
}
int main(int argc,char* argv[])
{
if(argc != 2)
err_exit("參數不正確!");
//切記加上0666否則其他進程無法獲取FIFO文件的讀取權限
if(mkfifo(FIFO_SERVER,O_CREAT | O_EXCL | 0666) == -1)
{
//判斷是否是FIFO文件已創建的錯誤
if(errno != EEXIST)
err_exit("Create FIFO error!");
}
int fdw = open(FIFO_SERVER,O_WRONLY);
if(fdw < 0)
err_exit("Open FIFO file error");
int fdr = open(argv[1],O_RDONLY);
if(fdr < 0)
err_exit("source file open error");
size_t n;
char buf[SIZE];
while((n = read(fdr,buf,SIZE)) > 0)
{
write(fdw,buf,n);
}
close(fdr);
close(fdw);
return 0;
}
#include
#include
#include
#include
#include
#include
#define SIZE 1024 //緩衝區大小
#define FIFO_SERVER "../FIFO" //FIFO文件路徑
//錯誤退出函數
void err_exit(char* msg)
{
printf("%s\n",msg);
exit(EXIT_FAILURE);
}
int main(int argc,char* argv[])
{
if(argc != 2)
err_exit("參數不正確!");
int fdr = open(FIFO_SERVER,O_RDONLY);
if(fdr < 0)
err_exit("Open FIFO file error");
int fdw = open(argv[1],O_WRONLY | O_CREAT,0666);
if(fdw < 0)
err_exit("purpose file open error");
size_t n;
char buf[SIZE];
while((n = read(fdr,buf,SIZE)) > 0)
{
write(fdw,buf,n);
}
close(fdr);
close(fdw);
unlink(FIFO_SERVER);//刪除FIFO文件
return 0;
}